我已经设置了一个Android Media Player,每当我启动(或重新启动)应用程序时都会运行,因为每当我按“播放音乐”时它都会播放音乐。
但是,我应该按“停止音乐”,然后“播放音乐”,不播放音乐,我必须重启我的应用程序。显然,这不太理想。我尝试过使用.prepare()方法(我通过首先搜索SO来查找此查询的答案),但它们似乎并不适用于我。我需要做什么才能使按钮始终工作,而不仅仅是一次会话?以下是“播放音乐”和“停止音乐”按钮的源代码。我们将非常感激地提供任何帮助。
我写的MediaPlayer代码在这里:
mediaPlayer = MediaPlayer.create(this,R.raw.insomnimix);
public void stopSoundButtonListener() {
Button stopSound = (Button) findViewById(R.id.stopSoundButton);
//When this method is called, stop the current sound playing.
stopSound.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (mediaPlayer.isPlaying() == true) {
Context context = getApplicationContext();
CharSequence text = "Stopping Music";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
mediaPlayer.stop();
} else {
Context context = getApplicationContext();
CharSequence text = "The music is already stopped.";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
现在这里是“播放音乐”按钮代码:
public void playSoundButtonListener() {
Button playSound = (Button) findViewById(R.id.playSoundButton);
//When this method is called, start the sound playing.
playSound.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (mediaPlayer.isPlaying() == false) {
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
}});
}