Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

android - How to properly use SoundPool on a game?

I'm having performance issues while using SoundPool. Everytime I play a sound, the frame rate drops. I added some logs and I can see on logcat that the "play" function sometimes takes 8ms.

I'm using *.ogg files and the SoundPool initialization is done on the app startup:

mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mSoundPool = new SoundPool(size, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mSoundPoolMap.put(index, mSoundPool.load(context, R.raw.shot, 1));

To play the sound, I use the following code (inside the game loop):

mSoundPool.play(id, streamVolume, streamVolume, 1, loop, 1f);

My questions are:

  • Should I call "play" on another thread, outside the game loop?
  • Should I call "play" through a service?
  • Am I doing anything wrong?

Thanks!


UPDATE:

I just tested playing the sound on another thread and playing the sound through a service, but the lag is still present.

Then I did the following tests: * play the sound on 1000ms intervals -> the lag always happens * play the sound on 200ms intervals -> the lag NEVER happens

How is that possible?!?!? After these tests, it seems that when there is nothing playing, SoundPool is resetting and when it is going to play again, it takes longer to initialize... very weird!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I solved the issue by playing a muted sound in loop:

mSoundPool.play(id, 0, 0, 1, -1, 1f);

The lag disappeared completely!

This doesn't seem the right thing to do, so if anyone knows how to explain this, please let us know!

More Info: http://www.thiagorosa.com.br/en/how-to/improve-soundpool-performance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...