gpt4 book ai didi

java - Android:连续播放多个音频文件时声音重叠

转载 作者:行者123 更新时间:2023-11-29 02:41:41 30 4
gpt4 key购买 nike

我正在尝试连续播放多个音频文件。我使用 MediaPlayer 类 来播放多个音频文件。但是,当我在模拟器或手机上测试时,我无法弄清楚为什么声音会重叠。我的代码的相关部分如下:

    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 秒内播放...)。知道为什么它会这样吗?

最佳答案

正如您在此处看到的那样,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");
}
});

关于java - Android:连续播放多个音频文件时声音重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43618817/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com