我有两个播放声音的按钮,编码如下:
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++;
}
});
@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以停止声音时,再次按下进行播放时,它就再也无法播放任何声音。
如何修改以上内容:
谢谢!
答案 0 :(得分:1)
尝试修改此代码:
@Override
public void onDestroy() {
super.onDestroy();
buttonSound1= MediaPlayer.create(x.this,R.raw.sound);
if(buttonSound1.isPlaying())
{
buttonSound1.stop();
buttonSound1.release();
}
}