我正在尝试为更长的音频文件创建一个音板,并且无法弄清楚如何停止音频文件并在不关闭活动的情况下再次启动它。假设每个音频文件都是一分钟。如果我播放第一个音频文件20秒并启动下一个音频文件,则第一个停止播放,第二个开始播放。但是,如果我再次单击第一个音频文件,则第二个停止播放而第一个不停止播放。我需要帮助。这让我疯了。
bAudio1 = (ImageButton) findViewById(R.id.bAudio1);
bAudio2 = (ImageButton) findViewById(R.id.bAudio2);
mpAudio1 = MediaPlayer.create(this, R.raw.audio1);
mpAudio2 = MediaPlayer.create(this, R.raw.audio2);
bAudio1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mpAudio1.isPlaying()) {
mpAudio1.stop();
} else {
if(mpAudio2.isPlaying()) { mpAudio2.stop(); }
mpAudio1.start();
}
}
});
bAudio2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mpAudio2.isPlaying()) {
mpAudio2.stop();
} else {
if(mpAudio1.isPlaying()) { mpAudio1.stop(); }
mpAudio2.start();
}
}
});
答案 0 :(得分:1)
这对我有用:
public class ExampleActivity extends Activity implements OnClickListener {
private Button button1;
private Button button2;
private MediaPlayer mediaPlayer1;
private MediaPlayer mediaPlayer2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// play first audio clip and stop the second if playing
if (mediaPlayer2 != null && mediaPlayer2.isPlaying()) {
mediaPlayer2.stop();
mediaPlayer2.release();
mediaPlayer2 = null;
}
mediaPlayer1 = MediaPlayer.create(this, R.raw.song1);
mediaPlayer1.start();
break;
case R.id.button2:
// play second audio clip and stop the first if playing
if (mediaPlayer1 != null && mediaPlayer1.isPlaying()) {
mediaPlayer1.stop();
mediaPlayer1.release();
mediaPlayer1 = null;
}
mediaPlayer2 = MediaPlayer.create(this, R.raw.song2);
mediaPlayer2.start();
break;
}
}
@Override
protected void onPause() {
super.onPause();
// stop the second if playing
if (mediaPlayer2 != null && mediaPlayer2.isPlaying()) {
mediaPlayer2.stop();
mediaPlayer2.release();
mediaPlayer2 = null;
}
// stop the first if playing
if (mediaPlayer1 != null && mediaPlayer1.isPlaying()) {
mediaPlayer1.stop();
mediaPlayer1.release();
mediaPlayer1 = null;
}
}