gpt4 book ai didi

android - 如何在android中同时播放多个声音

转载 作者:行者123 更新时间:2023-12-04 04:34:54 29 4
gpt4 key购买 nike

我尝试了以下代码,并且 3 个音符同时播放。该方法由单击按钮触发。然而,在下一次点击事件中,它只播放一个音符,应用程序崩溃。每次单击按钮时,我都想播放 3 个不同的音符。(我随机选择了那些)

    player = MediaPlayer.create(this, resIdFirstNote);
player.start();

player = MediaPlayer.create(this, resIdSecondNote);
player.start();

player = MediaPlayer.create(this, resIdThirdNote);
player.start();

player.release();

是播放器实例重载了吗?我应该以不同的方式释放它吗?
还是别的什么?

提前谢谢
莱昂

最佳答案

使用 android.media.SoundPool :

public class MyActivity extends Acticity implements SoundPool.OnLoadCompleteListener {
private SoundPool soundPool;
private final int maxPlaying = 4;
private final int volume = 1;
private final int priority = 1;
private final int no_loop = 0;
private final float normal_playback_rate = 1f;
private final Map<Integer, Integer> loadedSongsCache = new HashMap<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
soundPool = new SoundPool(maxPlaying, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(this);

playSong(R.raw.somethingSound);
playSong(R.raw.somethingSound2);
playSong(R.raw.somethingSound3);
}

private void playSong(int resourceId){
Integer sampleId = loadedSongsCache.get(resourceId);
if (sampleId != null) {
soundPool.play(sampleId, volume, volume, priority, no_loop, normal_playback_rate);
} else {
sampleId = soundPool.load(ColorMixActivity.this, songMix.getResourceId(), priority);
loadedSongsCache.put(songMix.getResourceId(), sampleId);
}
}

@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
if (status == 0)
soundPool.play(sampleId, volume, volume, priority, no_loop, normal_playback_rate);
}

@Override
protected void onDestroy() {
soundPool.release();
super.onDestroy();
}
}

关于android - 如何在android中同时播放多个声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19892150/

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