Professional Documents
Culture Documents
1 of 2
http://stackoverflow.com/questions/12266502/android-mediaplayer-stop-...
help
button1
it plays
I check on each button the other player if it's working and I stop it and play the clicked one
But If I click on same button twice it's keep first audio playing in the background and play another one again
I tried to check
isPlaying()
I want If I click on
button1
it play
sound1
My code:
package com.hamoosh.playaudio;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PlayaudioActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b= (Button) findViewById(R.id.button1);
Button b2= (Button) findViewById(R.id.button2);
final TextView t= (TextView) findViewById(R.id.textView1);
final MediaPlayer mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
final MediaPlayer mp1 = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp1.isPlaying()) {
mp1.stop();
}
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.stop();
}
mp1.start();
}
});
}
}
Hope if there any better code that can use multiple buttons as an array or something to not check each button and player every time.
android
media-player
12
29
47
2 Answers
27/03/2015 17:13
2 of 2
http://stackoverflow.com/questions/12266502/android-mediaplayer-stop-...
19
@SiKni8 You have to ask a new question, can't answer it here mario Aug 26 '13 at 13:34
@mario I figured it out. Thanks for the response. SiKni8 Aug 26 '13 at 13:35
According to the Media Player lifecycle, which you can view in the Android API guide,I think that
you have to call reset() instead of stop(), and after that prepare again the media player (use
only one)to play the sound from the beggining. Take also into account that the sound may have
finished, so I would also recommend to implement setOnCompletionListener() to make sure
that if you try to play again the sound it doesn't fail.
answered Sep 4 '12 at 15:26
Javier
83
27/03/2015 17:13