繁体   English   中英

Android:在活动被破坏时停止Mediaplayer

[英]android: stopping mediaplayer when the activity is destroyed

我有2个播放声音的按钮,其编码如下:

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);

...
}

然后在按钮上按:

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();  
} 

题:

当按钮1播放声音时,必须停止按钮2的声音,反之亦然。

当我完成活动(已销毁)时,声音仍在播放直到结束而没有停止。

我怀疑这是否是因为buttonSound1是内部创建onClickListener ,因而对破坏时,不能停止? 我试图删除此类MediaPlayer.create行,但是当按下按钮1停止声音时,再按一次播放时,它根本无法再播放任何声音。

如何修改以上内容,以便:

  1. 按钮1播放,然后必须停止按钮2,反之亦然
  2. 活动结束后,按钮1和2的声音将立即停止。

谢谢!

尝试修改此代码:

@Override
public void onDestroy() {
super.onDestroy();
buttonSound1= MediaPlayer.create(x.this,R.raw.sound);
if(buttonSound1.isPlaying())
{
  buttonSound1.stop();
  buttonSound1.release();
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM