我对编程很新,并且在遇到小问题时遇到困难。我创建了一个容易初始化并开始工作的对象,如何阻止该对象运行。
以下是我的代码:
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
animationFart();
playRandomSound();
}
private void playRandomSound() {
// TODO Auto-generated method stub
int randomInt = (new Random().nextInt(soundList.size()));
int sound = soundList.get(randomInt);
MediaPlayer mp = MediaPlayer.create(btn.getContext(), sound);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
});
如何通过按下按钮来停止此操作。
答案 0 :(得分:1)
全局定义MediaPlayer mp;
并使用mp.stop();
:
if (mp!=null && mp.isPlaying()) {
mp.stop();
}
答案 1 :(得分:-1)
使用此课程
public class AudioPlayer {
private MediaPlayer mediaPlayer;
public void play(Context context, int resId) {
stop();
mediaPlayer = MediaPlayer.create(context, resId);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mediaPlayer.start();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
public boolean isPlaying() {
return mediaPlayer != null;
}
}