我有很多Imageview在点击时播放声音,我设法播放它。 但问题是,当我想点击另一个应该播放另一个声音的图像时,它会停止声音但是如果点击同一个播放按钮我无法恢复。
到目前为止,我已经成功完成了以下代码:
audio1 = (ImageView) popupView.findViewById(R.id.lesson1_audio_gramar_1);
assert audio1 != null;
audio1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMediaPlayer == null) {
mMediaPlayer = MediaPlayer.create(Lesson1Activity.this, R.raw.lesson1);
}
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
audio1.setImageResource(R.drawable.ic_play_circle_filled_black_48dp);
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
mMediaPlayer.start();
audio1.setImageResource(R.drawable.ic_pause_circle_filled_black_48dp);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
audio2 = (ImageView) popupView.findViewById(R.id.lesson1_audio_gramar_2);
assert audio2 != null;
audio2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMediaPlayer == null) {
mMediaPlayer = MediaPlayer.create(Lesson1Activity.this, R.raw.lesson2);
}
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
audio2.setImageResource(R.drawable.ic_play_circle_filled_black_48dp);
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
mMediaPlayer.start();
audio2.setImageResource(R.drawable.ic_pause_circle_filled_black_48dp);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
答案 0 :(得分:0)
要播放其他曲目,请按照以下简单步骤操作:
if (mediaPlayer != null) {
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.reset()
mediaPlayer.setDataSource(new music to play);
mediaPlayer.prepare();
}
}
然后在mediaPlayer.start()
方法
onPrepared()