开发者

How to Sync Sounds using SoundPool

I have been trying to get a few sounds to play at the same time; currently i'm using a shared instance of SoundPool. I would like 1, 2 or 3 sounds to be played at the exact same time with no lag.

When calling SoundPool.play(...) X number of times in succession, the sounds are played in that order as one might think. what is the proper what to achieve this where i can prepare all of the sounds to be played at the same time and then play them as one?

Sudo Code:

SoundPool _soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

_soundPool.load(_context, soundId1, 1);
_sou开发者_运维问答ndPool.load(_context, soundId2, 1);
_soundPool.load(_context, soundId3, 1);

_soundPool.play(soundId1, vol, vol, 1, 0, 1f);
_soundPool.play(soundId2, vol, vol, 1, 0, 1f);
_soundPool.play(soundId3, vol, vol, 1, 0, 1f);


i done the sound pool for one sound at time it might help you. Android:sound pool and service

Thank you


You need to understand that SoundPool.load method is asyncronous, so when you call it 3 times in a row, and then call play, there is no garantee that this sounds actually loaded. So you need to wait until all sounds is loaded. For that use OnLoadCompleteListener:

fun loadAndPlay(soundPool: SoundPool, context: Context, resIds: IntArray) {
    val soundIds = IntArray(resIds.size) {
        soundPool.load(context, resIds[it], 1)
    }

    var numLoaded: Int = 0

    soundPool.setOnLoadCompleteListener { sPool, sampleId, status ->
        numLoaded++

        if (numLoaded == resIds.size) {
            soundPool.setOnLoadCompleteListener(null)

            for (id in soundIds) {
                soundPool.play(id, 1f, 1f, 1, 0, 1f)
            }
        }
    }
}

To use:

loadAndPlay(soundPool, context, intArrayOf(R.raw.sound_1, R.raw.sound_2, R.raw.sound_3))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜