开发者

Best way to play different sounds one at a time on iphone?

I have a bunch of sounds I want to play. Right now I'm using AVAudioPlayer. A new sound should start when the u开发者_StackOverflowser clicks a button. The url property of AVAudioPlayer is read-only. I'd rather not have to release and re-alloc the object every time I want a new sound played. What would be the best way to do this? Is there a different class I need to use?


The absolute easiest way to play sound is Playing UI Sound Effects or Invoking Vibration Using System Sound Services. Essentially you call AudioServicesCreateSystemSoundID() and AudioServicesPlaySystemSound(). Creating a system sound is relatively expensive and playback stops when it's disposed with AudioServicesDisposeSystemSoundID() anyway, so you really want to cache them:

  • Create them at app launch (or possibly the first time the sound is played). You can keep them in an NSDictionary keyed by sound file name and store the sound ID in an NSValue, or so.
  • If you can be bothered, dispose them when your app exits, is backgrounded, or on a memory warning.

The biggest caveat is that only a few sound formats are supported for "system sounds"; apple seems to recommend IMA4 (afconvert -f caff -d ima4 input.file output.caf and optionally -c 1 if you're happy with mono).

That said, it's pretty much perfect for playing short sounds provided you don't mind one-at-a-time sounds (it restarts playback if you play a sound while it's already playing). I suspect it's also played directly by the kernel (you can set a flag to make it continue playback when your app exits), which probably means it's more efficient CPU-wise. It might mix with sounds played by AVAudioPlayer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜