我试图连续播放多个音频文件。我使用MediaPlayer class
来播放多个音频文件。但是,当我在模拟器或手机上测试声音时,我无法弄清楚声音重叠的原因。我的代码的相关部分如下:
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秒内播放...)。知道它为什么会这样表现吗?
答案 0 :(得分:0)
正如您在此处看到的那样MediaPlayer是异步mPlayer1.prepareAsync();
你需要做的是从setOnCompletionListener
启动它们
之前的MediaPlayer。
像这样:
//init here
mPlayer1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mPlayer1.stop();
try {
mPlayer1.reset();
mPlayer2.setOnPreparedListener(new
MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
AppLog.logString("Start Playing Sound2");
mPlayer2.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
mPlayer1.release();
AppLog.logString("Stop Playing Sound1");
}
});