我要完成的工作是停止音乐,然后再次按播放按钮时,媒体播放器将播放音乐。
但是我现在面临的问题是按下停止按钮后,我无法再次播放音乐。
这是我的代码:
Button play,pause,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_beginagain);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
final MediaPlayer sound = MediaPlayer.create(Audio_BeginAgain.this, R.raw.beginagain);
final MediaPlayer mp = new MediaPlayer();
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sound.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sound.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sound.stop();
}
});
}
最佳答案
这正是阿卜杜勒·加富尔博士所说的。
每次您要重播MediaPlayer
时,都必须使用create()
对其进行新的初始化。
看下面的代码:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
代码复制自:Android MediaPlayer Stop and Play
关于android - 停止并重放音频文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31624259/