问题
I am playing some short sounds on my iPad like so: Play a short sound in iOS
I am using a caf
file which I can successfully play from the Finder. Now I went through quite a bit of a hassle trying to achieve the playback of the sound and I am curious what might be the problems which I don't seem to understand:
Option 1: When I create the SystemSoundID and then play it right away I don't hear anything on the device and the simulator.
Option 2: When I create an instance variable for the SystemSoundID and initialize it in
viewDidLoad
I manage to play sound but only on the iPad, not the Simulator.Option 3: Instead of using
SystemSoundID
I can also use AVAudioPlayer to playback a.wav
file which then works on both the iPad and the Simulator but here I need to create the AVAudioPlayer inviewDidLoad
otherwise I won't get any sound if I do everything in one go.
The best option currently seems to be Option 3
because it works on both the Simulator and the iPad, but because I need to pre-initialize the Player I would need an AVAudioPlayer
instance for every different sound that I want to play, which does not seem to be very memory-wise...
Is there something that I am missing and is it possible to play sounds on both platforms using the AudioToolbox
framework (Option 1 & Option 2)
回答1:
I wrote a library to simplify all this. It wraps AVAudioPlayer, and works fine on both the device and simulator.
https://github.com/nicklockwood/SoundManager
The code is fairly straightforward, although I do some semi-clever stuff to initialise the audio player. If you don't want to use the library you can just copy the code.
A word of warning though - the simulator throws some odd exceptions internally whenever you use AVAudioPlayer. They don't affect the app at all, but if you have enabled break-on-exceptions in Xcode then the app will drop into the debugger a few times during startup and you'll have to manually resume, which may freak you out if you're not expecting it.
来源:https://stackoverflow.com/questions/10351199/sound-does-only-work-on-device-but-not-in-simulator