andrewb
andrewb

Reputation: 3095

Playing sounds in Android in certain order

In an Android app I am using MediaPlayer to play sound files.

This is just for personal use and will not be published.

I have several references to the sound files:

MediaPlayer dooropen = MediaPlayer.create(MainActivity.this, R.raw.dooropen);
MediaPlayer doorclose = MediaPlayer.create(MainActivity.this, R.raw.doorclose);
//...

For example the length of the dooropen sound clip is 2 seconds so after I play it I sleep for 2.5 seconds and then play the doorclose sound clip, like so

dooropen.start();
try{ Thread.sleep(2500); }catch(InterruptedException e){ }
doorclose.start();

The issue I am having is some of my sound files are not playing in the order I have them in.

There does not seem to be any reason why certain sound files do not play, because if I play them at the top of my onCreate() procedure they all play, it is only when I try and play them in a certain order.

Upvotes: 0

Views: 573

Answers (3)

Twitter khuong291
Twitter khuong291

Reputation: 11672

If you want to play sound in order, try this:

        mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp2.start();
            }
        });
        mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp3.start();
            }
        });
        mp3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp1.start();
            }
        });

Upvotes: 0

Arslan Ashraf
Arslan Ashraf

Reputation: 867

Yes you can use MediaPlayer along with oncompletionListener or you may try reseting the mediaplayer after one audio is completed. example code here. You may also use session id to keep track of which file was playing and which to start now.

    mPlayer = new MediaPlayer();
  //set other attributes here
    mPlayer.setAudioSessionId(1);
    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            //check which audio session was playing and set new datasource and session
        mPlayer.reset();
       //set other data source here and different session id

        }
    });

Hope it solves your problem.

Upvotes: 0

Aegis
Aegis

Reputation: 5791

You should implement the setOnCompletionListener() of the mediaplayer to get a callback when playback has completed and then load another audio file that needs to start playing.

See MediaPlayer Documentation about the mediaplayer state.

Upvotes: 2

Related Questions