按下开始按钮的同时开始播放mp3文件,但按下“停止”按钮时不会停止,我已经通过几个例子但找不到确切的解决方案
public Button play;
public Button stop;
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button)findViewById(R.id.played);
stop = (Button)findViewById(R.id.stopped);
play.setOnClickListener(this);
stop.setOnClickListener(this);
}
public void onClick(View v) </br>
{
mp = MediaPlayer.create(this,R.raw.you);
if(v==play && !mp.isPlaying()){
mp.start();
}
//below part of code executes but doesn't stop the player
else if (v==stop){
mp.stop();
mp.release();
}
}
答案 0 :(得分:0)
mp = MediaPlayer.create(this,R.raw.you);
每次调用它时, create都会返回一个新实例。因此,您在stop()
的实例上调用mp
,与您调用start()
的实例不同。你应该在onCreate
例如
答案 1 :(得分:0)
这样做:
public void onClick(View v) {
switch (v.getId()) {
case R.id.played:
if(mp==null || !mp.isPlaying()){
mp = MediaPlayer.create(this,R.raw.you);
mp.start();
}
break;
case R.id.stopped:
if(mp!=null && mp.isPlaying()){
mp.stop();
mp.release();
}
break
default:
break;
}
}