Home » Android » android – Playing audio files one after another

android – Playing audio files one after another

Posted by: admin June 15, 2020 Leave a comment

Questions:

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();

        }
    }
How to&Answers:

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.

Answer:

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);
    }
});

}

Answer:

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
     }
});

Answer:

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(); 

Answer:

 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();
       }

Answer:

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;
    }
}

Answer:

For me the issue was that I was calling mediaPlayer.prepare() without first calling mediaPlayer.reset().

All good now.