我想在我的android应用程序中回放mp3文件(半秒)。我能够在模拟器上做到这一点,但在手机上它们都是相互重叠的。 我使用过OnCompletionListerner并停止了Mediaplayer 以下是我的一个mp3文件的代码:
mPlayer = MediaPlayer.create(MainActivity.this, R.raw.a10);
mPlayer.start();
mPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mPlayer) {
// TODO Auto-generated method stub
mPlayer.stop();
}
});
有人可以建议任何方法来阻止重叠吗?
答案 0 :(得分:0)
请尝试以下示例:
MediaPlayer mp1, mp2;
Timer timer;
// Create two different instances of mediaplayer
mp1 = MediaPlayer.create(MainActivity.this, R.raw.a1);
mp2 = MediaPlayer.create(MainActivity.this, R.raw.a2);
// Create the timertask
timer = new Timer("mytimer");
timer.schedule(timertask1, 1000);
<强> onCompletionListeners:强>
// Completion listener for Audio file 1.
mp1.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(final MediaPlayer cim) {
//On completion of first audio, release the resources of mediaplayer
mp1.release();
mp1 = null;// free up memory
// Start the timertask of 2nd audio file
timer = new Timer("mytimer");
timer.schedule(timertask2, 1000);
}
});
mp2.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(final MediaPlayer cim) {
//On completion of 2nd audio, release the resources of mediaplayer
mp2.release();
mp2 = null;
// Start the timertask of 1st audio file or nxt audio file if you want to play file or simplly you can stop here.
timer = new Timer("mytimer");
timer.schedule(timertask1, 1000);
}
});
计时器任务:
private TimerTask timertask1 = new TimerTask() {
@Override
public void run() {
mp1.start();
}
};
private TimerTask timertask2 = new TimerTask() {
@Override
public void run() {
mp2.start();
}
};
注意:强>
给出的示例仅考虑两个音频文件,因此两个特定的onCompletionlisteners和timertasks。但是我建议你使用通用代码来创建mediaplayer实例,onCompletionlistener和timertask。