我试图连续播放多个音频文件。我使用MediaPlayer class来播放多个音频文件。但是,当我在模拟器或手机上进行测试时,我无法弄清为什么声音重叠。我的代码的相关部分如下:Android:连续播放多个音频文件时声音重叠
private MediaPlayer mPlayer1 = new MediaPlayer();
private MediaPlayer mPlayer2 = new MediaPlayer();
private AudioManager audioManager;
public void permissionGrantedActions() {
Uri uri1=Uri.parse("android.resource://com.android.packageName/" + mFile1);
try{mPlayer1.setDataSource(getActivity(), uri1);
}catch (IOException e) {
e.printStackTrace();
}
mPlayer1.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mPlayer1.prepareAsync();
mPlayer1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
AppLog.logString("Start Playing Sound1");
mPlayer1.start();
}
});
mPlayer1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mPlayer1.stop();
try {
mPlayer1.reset();
} catch (Exception e) {
e.printStackTrace();
}
mPlayer1.release();
AppLog.logString("Stop Playing Sound1");
}
});
mPlayer2.reset();
Uri uri2=Uri.parse("android.resource://com.android.packageName/" + mFile2);
try {
mPlayer2.setDataSource(getActivity(), uri2);
}catch (IOException e) {
e.printStackTrace();
}
mPlayer2.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mPlayer2.prepareAsync();
mPlayer2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
AppLog.logString("Start Playing Sound2");
mPlayer2.start();
}
});
mPlayer2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mPlayer2.stop();
try {
mPlayer2.reset();
} catch (Exception e) {
e.printStackTrace();
}
mPlayer2.release();
AppLog.logString("Stop Playing Sound2");
}
});
...
}
使用上面的方法,声音是重叠的(每个音频文件约1秒长,使用此代码时,所有4个音频文件都在1秒内打出.. )。任何想法为什么这样做?
2017-04-25
Zack