Android soundpool timing

对着背影说爱祢 提交于 2019-12-06 03:02:55

Although this is an old question, I thought I would post something here since I couldn't find a solution to this problem online but did come up with something of a solution...

I get the duration of each sound (using MediaPlayer) when my app starts up, and store the R.id.sound_name value and the duration together. I can then play the sounds using the SoundPool.

Code to get duration:

private long getSoundDuration(int rawId){
  MediaPlayer player = MediaPlayer.create(context, rawId);
  int duration = player.getDuration();
  return duration;
}

In my sound class, I then play the sound as usual then sleep for the duration. Pretty simple stuff.

Seems to work well. Gives me the advantages of low-latency from SoundPool, plus ability to chain things.

A couple things to note:

  • Don't get the duration each time, as creating a MediaPlayer has overhead.
  • Durations are taken from file metadata -- ogg's work great for me, but I can't vouch for anything else.

Make sure you have enough Streams. in the SoundPool constructor, the first argument is MaxStreams. Set that to whatever you seem fit. 8 or so should be enough i guess... but you might need more, depending on your sounds.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!