Reputation: 43
I have recently tried to create a button that says "Play", and when this button is pressed, I wanted it to play the music then change the text to "Stop", but it throws an error and quits the app. Here is my code:
mPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ourMusic.isPlaying()){
ourMusic.pause();
mDisplay.setText("Play");
}else{
ourMusic = MediaPlayer.create(MainActivity.this, R.raw.killthenoise);
ourMusic.start();
mDisplay.setText("Stop");
}
}
});
So if you press the button once it should play, press it again it should stop the music. There is no errors in the actual coding. Here is my logcat: http://pastie.org/7970711
I am new to this stuff, so I don't know too much of whats going on. Any help would be appreciated.
Upvotes: 0
Views: 2092
Reputation: 516
Add a global variable boolean flag=false;
if(flag==false)
{
mp=MediaPlayer.create(this, R.raw.abc);
mp.start();
playbutton.setText("Pause");
flag=true;
}
else if(mp.isPlaying()&&flag==true)
{
mp.pause();
playbutton.setText("Play");
flag=false;
}
This code will work if you want to use the same button as PLAY/PAUSE in your app. Hope this helps.
Upvotes: 0
Reputation: 8049
Use this instead:
@Override
public void onClick(View v) {
if (ourMusic == null) {
ourMusic = MediaPlayer.create(MainActivity.this, R.raw.killthenoise);
}
if(ourMusic.isPlaying()){
ourMusic.pause();
mDisplay.setText("Play");
}else{
ourMusic.start();
mDisplay.setText("Stop");
}
}
Basically don't:
ourMusic
everytime there is a click to playourMusic
when it isn't instantiated.Upvotes: 2