Question

I have 2 buttons that play sounds, with the coding as follows:

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout1);

    buttonSound1 = MediaPlayer.create(Violin.this,R.raw.violin1);
    buttonSound2 = MediaPlayer.create(Violin.this,R.raw.violin2);

...
}

Then on button press:

button1.setOnClickListener(new OnClickListener()
{
     public void onClick(View view)
     {                                       
         if (b1 %2 == 0)
         {
             button1.setText("STOP!");
             button2.setText("Song 2");
             if(buttonSound1.isPlaying()) buttonSound1.stop();
             if(buttonSound2.isPlaying()) {buttonSound2.stop(); b2++;}                   
             buttonSound1 = MediaPlayer.create(Violin.this,R.raw.violin1);               
             buttonSound1.start();   
         }
         else
         {
             button1.setText("Song 1");
             button2.setText("Song 2");
             if(buttonSound1.isPlaying()) buttonSound1.stop();
             if(buttonSound2.isPlaying()) {buttonSound2.stop(); b2++;}                   
         }
         b1++;   
     }
});

OnDestroy:

@Override  
protected void onDestroy() 
{    

    // stop the sounds
    if(buttonSound1.isPlaying()) buttonSound1.stop(); buttonSound1.release();  
    if(buttonSound2.isPlaying()) buttonSound2.stop(); buttonSound2.release();  

    super.onDestroy();  
} 

Question:

When the button 1 is playing sound, button 2's sound must be stopped, vice versa.

When I finish the activity (destroyed), the sound is still playing till its end without stopped.

I doubt whether this is because the buttonSound1 is created inside the onClickListener and hence cannot be stopped when on destroyed? I have tried to remove such MediaPlayer.create lines but then when the button 1 is pressed to stop the sound, when pressed again to play, it simply cannot play any sounds anymore.

How could the above be modified such that:

  1. button 1 playing then button 2 must be stopped, vice versa
  2. button 1 and 2 sounds will stopped immediately when the activity is finished.

Thanks!

Was it helpful?

Solution

Try to modify this code:

@Override
public void onDestroy() {
super.onDestroy();
buttonSound1= MediaPlayer.create(x.this,R.raw.sound);
if(buttonSound1.isPlaying())
{
  buttonSound1.stop();
  buttonSound1.release();
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top