Abdullah Alhazmy
Abdullah Alhazmy

Reputation: 627

Lag between two sound "Mediaplayer" android

I want to play two sounds. I'm using this code but there's lag between the two sounds for about 2s. I want to play the second directly when the first sound is finished. How can I do that?

MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.s83); 
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
    public void onCompletion(MediaPlayer mp2){   
        mp2 = MediaPlayer.create(getApplicationContext(),R.raw.ss); 
        mp2.start();
    }
});

Upvotes: 1

Views: 1944

Answers (2)

ianhanniballake
ianhanniballake

Reputation: 199795

Android 4.1 (v16) adds MediaPlayer.setNextMediaPlayer which was added to allow gapless playing as per the feature list. Prior to that, there is always a small delay between onCompletion and starting another MediaPlayer due to buffering. Creating the second MediaPlayer before onCompletion might help as well (and would be required for using setNextMediaPlayer anyways).

Upvotes: 3

Voicu
Voicu

Reputation: 17850

Try this:

Make mp2 a MediaPlayer class field and then use this code:

mp2 = MediaPlayer.create(getApplicationContext(),R.raw.ss); 
MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.s83); 
mp.start();

mp.setOnCompletionListener(new OnCompletionListener() {
    public void onCompletion(MediaPlayer mp){   
        YourActivityClass.this.mp2.start();
    }
});

It will at least create the second MediaPlayer object and prepare() before the first sound is played, so you gain some time there.

Upvotes: 0

Related Questions