Search code examples
androidaudioandroid-mediaplayermedia

3 audios at the same time with Android MediaPlayer


I am trying to play 3 audios width Android but not at the same time, my code is the next one:

                for (Word w : wordsList){
                    String path = Parameters.PATH_AUDIO + "/" + w.getAudioPath();
                    Uri audioPath = Uri.parse(path);
                    MediaPlayer audio1 = MediaPlayer.create(context, audioPath);
                    audio1.start();
                }

But all audios start to play at least at the same time. I need something like audio1.wait() or audio1.sleep or someone like this.


Solution

  • You might want to consider using setOnCompletionListener:

    audio1.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
    public void onCompletion(MediaPlayer player) {
    
          //do something when audio is finished   
    
    }});
    

    Here's an example (didn't have the chance to try it though):

    Decalre these in the class level:

    int index = 0;
    MediaPlayer audio1;
    

    and then:

    try {
            audio1 = MediaPlayer.create(this, Uri.parse(yourList.get(index)));
            audio1.start();
            index++;
    
            audio1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer player) {
    
                    if (index < yourList.size()) {
                        audio1.reset();
                        audio1 = MediaPlayer.create(MainActivity.this,
                                Uri.parse(yourList.get(index)));
                        audio1.start();
                        index++;
                    }
                    else
                    {
                        //release it
                    }
    
                }
            });
    
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }