我有一个布局,其中显示了多个按钮。分别按下按钮一个声音播放。我的代码就像但不起作用: -
@Override
public void onClick(View view) {
resetPlayer();
int index = 0;
if (view.equals(objbutton1))
index = R.raw.sound1;
while (true) {
this.objplayer = MediaPlayer.create(this, index);
this.objplayer.setLooping(false);
this.objplayer.start();
this.objplayer
.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
MainActivity.this.objplayer.release();
MainActivity.this.objplayer = null;
}
}
);
if(view.equals(objbutton2))
{
index=R.raw.sound2;
continue;
}
if(view.equals(objbutton3))
{
index=R.raw.sound3;
continue;
}
if(view.equals(objbutton4))
{
index=R.raw.sound4;
continue;
}
if(view.equals(objbutton5))
{
index=R.raw.sound5;
continue;
}
break;
}
}
private void resetPlayer() {
if (this.objplayer != null) {
if (this.objplayer.isPlaying())
this.objplayer.stop();
this.objplayer.release();
this.objplayer = null;
}
应用程序只播放一种声音,单击其他按钮时不会更改声音
答案 0 :(得分:0)
使用此
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
...一样
private MediaPlayer mp; // declare it in public area.
public void onClick(View view) {
int index = 0;
if (view.equals(objbutton1)){
index = R.raw.sound1;
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
if(view.equals(objbutton2))
{
index=R.raw.sound2;
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
if(view.equals(objbutton3))
{
index=R.raw.sound3;
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
if(view.equals(objbutton4))
{
index=R.raw.sound4;
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
if(view.equals(objbutton5))
{
index=R.raw.sound5
if(mp !=null && mp.isPlaying()) mp.stop();
mp = MediaPlayer.create(getApplicationContext(), index);
mp.start();
}
}
在onDestroy()
中放置此mp.release();