im newbie here, can you help me?? i want to play all song in my raw folder sequentially, after all song finished playing i want no looping.
i have tried this code but it keeps looping after allsong playing
{
int [] sound;
int soundke = 0;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kubus);
sound = new int[] {R.raw.swoosh2, R.raw.swoosh1, R.raw.swoosh2};
mediaPlayer = MediaPlayer.create(kubus.this, sound[0]);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
play();
}
});
}
private void play () {
soundke = (soundke + 1) % 3;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(sound[soundke]);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
} catch (IOException e) {
}
}
it still keeps looping after all song playing. i want not looping after all song playing, thanks for your helping
int [] sound;
int soundke = 0;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kubus);
sound = new int[] {R.raw.swoosh2, R.raw.swoosh1, R.raw.swoosh2};
mediaPlayer = MediaPlayer.create(kubus.this, sound[0]);
mediaPlayer.setLooping(false);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if(soundke < sound.length-1){
play(++soundke);
}else{
soundke=0;
mediaPlayer.stop();
}
}
});
}
private void play (int track) {
//soundke = (soundke + 1) % 3;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(sound[track]);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.setLooping(false);
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
} catch (IOException e) {
}
}
Related
when I play a sound file the sounds stops after a second. How can I make sure the sound keeps playing?
final Button BtPlaySound = (Button) resultdialog.findViewById(R.id.BtPlaySound);
BtPlaySound.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//play sound
/*final MediaPlayer player = MediaPlayer.create(ActivityMain.this, R.raw.r);
player.setLooping(true); // Set looping
player.setVolume(100,100);
player.start();
*/
Context context = ActivityMain.this;
MediaPlayer mp = MediaPlayer.create(context, R.raw.r);
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.r);
}
mp.start();
} catch(Exception e) {
e.printStackTrace();
}
//End Of PlaySoundFunction
}
I need to play multiple (correct :2 ) mp3 files loaded from my assets when a button is clicked. If the button is again clicked 2 new songs should be played and the old ones should be stopped immidiatelly.The process is on going...
At the moment I have achieved this by stupidly creating 2 mediaPlayer instances in 2 separate methods that basically have the same body .
The caller is an onTouch method and ,within it, first I call method 1 ,then sleep for 2 secs ,then call method 2. I m sure there must be a way for this to be more elegant code? For example I have implemented some listeners that are just sitting there (Actually tried to make this work but totally screwed up with Illegal States all over the place ). Ideally I would like to use 1 MediaPlayer and one method for playing every sound in my app.
int carouzelIndex = 0
#Override
public boolean onTouch(MotionEvent e, int scaledX, int scaledY) {
...
if (e.getAction() == MotionEvent.ACTION_UP) {
carouzelIndex++;
Assets.playMusic1("music1.ogg",false);
Thread thread = new Thread(){
public void run(){
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assets.playMusic2("music2.ogg",false);
}
}
}
}
Now my player methods 1 and 2 (playMusic1() and playMusic2() )are the same. Both are instansiating different MediaPlayers and for the shake of simplicity I write just one copy in the post
Public class Assets
MediaPlayer mediaPlayer;
public static void playMusic(String filename, boolean looping) {
AssetFileDescriptor afd = null;
Log.d("Assets", "playing music");
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
try {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
afd = GameMainActivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying())
mp.start();
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
}
});
mediaPlayer.setOnInfoListener(new OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
For immediate playback you need two MediaPlayer set up and chained together via OnCompletionListener
You can do it like this:
Note that I also deleted some unnecessary overrides, you might add them again if you need them.
Public class Assets{
MediaPlayer mediaPlayer;
MediaPlayer mediaPlayer2;
boolean mediaplayer2prepared = false;
boolean mediaplayer1finished = false;
public static void playMusic(String filename, boolean looping, String filename2, boolean looping2) {
AssetFileDescriptor afd = null;
Log.d("Assets", "playing music");
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
mediaplayer1finished = false;
}
if (mediaPlayer2 == null) {
mediaPlayer2 = new MediaPlayer();
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.setLooping(looping);
mediaplayer2prepared = false;
}
try {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
mediaplayer1finished = false;
}
if (mediaPlayer2 != null) {
mediaPlayer2.stop();
mediaPlayer2.release();
mediaPlayer2 = new MediaPlayer();
mediaplayer2prepared = false;
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.setLooping(looping);
}
afd = GameMainActivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying())
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
if(mediaplayer2prepared)
mediaplayer2.start();
mediaplayer1finished = true;
}
});
mediaPlayer.prepareAsync();
afd2 = GameMainActivity.assets.openFd(filename2);
mediaPlayer2.setDataSource(afd2.getFileDescriptor(),
afd2.getStartOffset(), afd2.getLength());
afd2.close();
mediaPlayer2.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
mediaplayer2prepared = true;
if(mediaplayer1finished && !mp.isPlaying()){
mp.start();
}
}
});
mediaPlayer2.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
}
});
mediaPlayer2.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
}
To start both mediaplayers in succession simply do Assets.playMusic("music1.ogg",false, "music2.ogg",false);
You can try something like this. Use a single mediaplayer in a single thread. It is an asynchronous operation so it will go on also if the thread is paused. I think it would work.
private Thread t = null;
private MediaPlayer mediaPlayer;
...
Button b=findViewById(R.id.yourButtonId);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//if button had previously clicked stop audio reproduction
if(mediaPlayer.isPlaying()) mediaPlayer.stop();
if(t.isAlive()) t.stop();
String[] files;
//Here you have to set your filenames in the array
...
...
//Now play that audio
playMusic(files, false);
}
});
...
protected static void playMusic(String[] files, boolean looping){
AssetFileDescriptor afd = null;
Log.e("Assets", "Playing music");
t=new Thread(){
#Override
public void run(){
//Initialize mediaPlayer
for(String filename:files){
mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
afd = GameMainAcivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength());
afd.close();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp){
if(!mp.isPlaying()) mp.start();
}
});
//while audio is playing wait in this position
while(mediaPlayer.isPlaying()){
this.wait(100);
}
//now loop can restart with the other filename that has
//to be reproduced
}
}
};
t.start();
}
i'm adding multiple audio files using
try {
MediaPlayer mp = MediaPlayer.create(context, R.raw.play);
audioArr[0] = mp;
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
and releasing media in a function as
for (MediaPlayer media : audioList) {
if (media != null) {
if(media.isPlaying())
media.stop();
media.release();
media = null;
}
}
stil i'm not able to play multiple audio file in my application,first time playing with audio,so kindly guide
Try this :
void addSongs()
{
File songs = new File(sdPath); //sdPath is the path of your audio files
if(songs.listFiles(new SongFilter()).length > 0)
{
for(File file : songs.listFiles(new SongFilter()))
{
vector.add(file.getName());
}
arrayAdapter.setNotifyOnChange(true); //arrayAdapter Array Adapter
songList.setAdapter(arrayAdapter); //songList is a ListView
}
}
SongFilter Class like this :
class SongFilter implements FilenameFilter
{
public boolean accept(File dir, String filename)
{
return (filename.endsWith(".mp3"));
}
}
buttonSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// play another sound here.do your stuff whatever you want to do
mp.stop();
}
});
public class AudioActivity extends Activity implements MediaPlayer.OnCompletionListener {
int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {##}
private void start(){
songs= new int[] {R.raw.s1,R.raw.s2,R.raw.s3,R.raw.s4};
mediaPlayer = MediaPlayer.create(this, songs[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
**// This is the completion listener registered with mediaplayer instance.**
playNextSong();
}
private void playNextSong()
{
current_index = (current_index +1)% songs.length;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);
if(current_index!=0){
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e){}
catch (IllegalStateException e){}
catch (IOException e){}
}else{
mediaPlayer.stop();
}
}
}
I have a list of audio files like this,
int music_numbers[] = { R.raw.one, R.raw.two, R.raw.three, R.raw.four,
R.raw.five, R.raw.six, R.raw.seven, R.raw.eight, R.raw.nine };
I need to play this one by one - when i send 100 to this play_numbers method - i am intend to play digit wise..
I have done this - but i unable to do this one after another..
private void _play_numbers(final String i) {
// TODO Auto-generated method stub
mPlayer = MediaPlayer.create(PlayFileActivity.this, R.raw.payment);
mPlayer.start();
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mPlayer.stop();
myDigit = i.charAt(1) + "";
_function_play_file(Integer.parseInt(myDigit));
}
});
}
in _function_play_file - i have this
void _function_play_file(int files) {
switch (files) {
case 0:
mPlayer = MediaPlayer.create(this, music_numbers[0]);
mPlayer.start();
case 1:
mPlayer = MediaPlayer.create(this, music_numbers[1]);
mPlayer.start();
case 2:
mPlayer = MediaPlayer.create(this, music_numbers[2]);
mPlayer.start();
case 3:
mPlayer = MediaPlayer.create(this, music_numbers[3]);
mPlayer.start();
case 4:
mPlayer = MediaPlayer.create(this, music_numbers[4]);
mPlayer.start();
case 5:
mPlayer = MediaPlayer.create(this, music_numbers[5]);
mPlayer.start();
case 6:
mPlayer = MediaPlayer.create(this, music_numbers[6]);
mPlayer.start();
case 7:
mPlayer = MediaPlayer.create(this, music_numbers[7]);
mPlayer.start();
case 8:
mPlayer = MediaPlayer.create(this, music_numbers[8]);
mPlayer.start();
case 9:
mPlayer = MediaPlayer.create(this, music_numbers[9]);
mPlayer.start();
case 10:
mPlayer = MediaPlayer.create(this, music_numbers[10]);
mPlayer.start();
}
}
You need to set an onCompletionListener to each and start the next one on completion.
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// Code to start the next audio in the sequence
}
});
The best way to achieve this is to create a class that implements OnCompletionListener which handles the onCompletion and receives the next file to play. This way you can instantiate it nicely in your code.
Of course, don't forget your break; in the cases above.
Use a queue for holding the numbers to be played.
private void _play_numbers(final String i) {
// e.g '100': put '1', '0', '0' in a Queue after converting to digits
Queue queue = new LinkedList();
//Use the add method to add items.
myDigit = // remove next digit from queue..
_function_play_file(myDigit);
}
void _function_play_file(int files) {
switch(files) {
case 0:
mPlayer = MediaPlayer.create(PlayFileActivity.this, R.raw.payment);
mPlayer.setOnCompletionListener(completeListener );
mPlayer.start();
break;
.....
}
OnCompletionListener completeListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
myDigit = // remove next digit from queue..
if (myDigit != -1) // if queue is not empty..
_function_play_file(myDigit);
}
});
}
This code works for me,but i place the audio files in assets folder:
//define a variable to be used as index.
int audioindex = 0;
//Extract the files into an array
String[] files = null;
files = assetManager.list("audiofiles");
mp.setOnCompletionListener(new OnCompletionListener(){
// #Override
public void onCompletion(MediaPlayer arg0) {
// File has ended, play the next one.
FunctionPlayFile(files[audioindex]);
audioindex+=1; //increment the index to get the next audiofile
}
});
This is working code for playing songs in continue loop
public class MainActivity extends Activity
{
private int[] tracks = {R.raw.explosion,R.raw.pianothingy_one,R.raw.car_horn_x};
int mCompleted = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = MediaPlayer.create(this, tracks[0]);
mp.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mCompleted++;
mp.reset();
if (mCompleted < tracks.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted>=tracks.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp.release();
mp = null;
}
}
});
mp.start();
use PlayMedia Like this
int[] soundIDs = {R.raw.yes, R.raw.eat};
PlayMedia playAudio = new PlayMedia(context,soundIDs);
playAudio.execute();
and define PlayMedia Class Like this
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.util.Log;
public class PlayMedia extends AsyncTask<Void, Void, Void> {
private static final String LOG_TAG = PlayMedia.class.getSimpleName();
Context context;
private MediaPlayer mediaPlayer;
int[] soundIDs;
int idx =1;
public PlayMedia(MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
}
public PlayMedia(final Context context, final int[] soundIDs) {
this.context = context;
this.soundIDs=soundIDs;
mediaPlayer = MediaPlayer.create(context,soundIDs[0]);
setNextMediaForMediaPlayer(mediaPlayer);
}
public void setNextMediaForMediaPlayer(MediaPlayer player){
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if(soundIDs.length>idx){
mp.release();
mp = MediaPlayer.create(context,soundIDs[idx]);
setNextMediaForMediaPlayer(mp);
mp.start();
idx+=1;
}
}
});
}
#Override
protected Void doInBackground(Void... params) {
try {
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "", e);
} catch (SecurityException e) {
Log.e(LOG_TAG, "", e);
} catch (IllegalStateException e) {
Log.e(LOG_TAG, "", e);
}
return null;
}
}
For me the issue was that I was calling mediaPlayer.prepare() without first calling mediaPlayer.reset().
All good now.
MediaPlayer mediaplayer = new MediaPlayer();
setSound(file );
try {
if(mediaplayer != null)
{
mediaplayer.stop();
mediaplayer.release();
}
mediaplayer.setDataSource(getResources().openRawResourceFd(file)
.getFileDescriptor());
mediaplayer.prepare();
mediaplayer = MediaPlayer.create(getBaseContext(), now);
mediaplayer.start();
mediaplayer.setLooping(false);
mediaplayer.setLooping(true); //sequence playing
} catch (NullPointerException e) {
e.printStackTrace();
}
I have 5 songs which i need to play one after the other, and it must loop from the first song after finishing the 5th song.
How do I use the MediaPlayer to achieve this?
public class MediaPlayerExample extends Activity implements MediaPlayer.OnCompletionListener {
int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
songs= new int[] {R.raw.song1,R.raw.song2,R.raw.song3,R.raw.song4};
mediaPlayer = MediaPlayer.create(this, songs[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
play();
}
private void play()
{
current_index = (current_index +1)% 4;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IllegalStateException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IOException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
}
}
Simple:
int[] songs = new int[]{R.raw.ab_hai_hamari_bari, R.raw.ab_khel_jamay_ga, R.raw.ab_khel_ke_dikha_psl_official_song, R.raw.chakka_choka_islamabad_united, R.raw.dil_dil_pakistan_junaid, R.raw.duniya_se_aagay, R.raw.hai_jazba_junoon_tho_himmat_na_haar, R.raw.hum_hain_pakistani_junaid, R.raw.jeet_ki_lagan, R.raw.jeetay_ga_pakistan_dedicate, R.raw.josh_e_junoon_pakistan_cricket, R.raw.karachi_kings_official, R.raw.lahore_qalandar_official, R.raw.multan_sultan_official, R.raw.peshawar_zalmi, R.raw.quetta_gladiator, R.raw.stand_up_for_the_champions};
you need to use CountDownTimer for this. CountDown timer has give you facility to do this one by one ::
MediaPlayer mp_xmPlayer2 = new MediaPlayer();
mp_xmPlayer2 = MediaPlayer.create(this, R.raw.bg_music_wav);
for(int i=0;i<5;i++)
{
CountDownTimer cntr_aCounter = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
mp_xmPlayer2.start();
}
public void onFinish() {
//change music name
}
};
cntr_aCounter.start();
}