I have a performance-intensive iPhone game I would like to add sounds to. There seem to be about three main choices: (1) AVAudioPlayer
, (2) Audio Queues and (3) OpenAL. I’d hate to write pages of low-level code just to play a sample, so that I would like to use AVAudioPlayer
. The problem is that it seems to kill the performace – I’ve done a simple measuring using CFAbsoluteTimeGetCurrent
and the play
message seems to take somewhere from 9 to 30 ms to finish. That’s quite miserable, considering that 25 ms == 40 fps.
Of course there is the prepareToPlay
method that should speed things up. That’s why I wrote a simple class that keeps several AVAudioPlayer
s at its disposal, prepares them beforehand and then plays the sample using the prepared player. No cigar, still it takes the ~20 ms I mentioned above.
Such performance is unusable for games, so what do you use to play sounds with a decent performance on iPhone? Am I doing something wrong with the AVAudioPlayer
? Do you play sounds with Audio Queues? (I’ve written something akin to AVAudioPlayer before 2.2 came out and I would love to spare that experience.) Do you use OpenAL? If yes, is there a simple way to play sounds with OpenAL, or do you have to write pages of code?
Update: Yes, playing sounds with OpenAL is fairly simple.
Check the game settings to make sure the music and sounds are turned on. Force stop and restart the game: double click the home button (or for iPhone X: swipe up from the bottom edge and pause in the center of the screen), find the game and swipe up on the game. Open the game again. Turn your device off and on again.
Make sure your device is not muted and that the volume is high enough. Make sure your music player is turned off. Try plugging in and unplugging your headphones.
Go to Settings > Sounds and drag the Ringer And Alerts slider to turn the volume up. If you hear sound from the speaker, follow the rest of these steps. If you can't hear sound from the speaker, contact Apple Support. If your device has a Ring/Silent switch, make sure it's set to ring.
AVAudioPlayer is very marginal for game audio. Tackling AudioQueue or OpenAL by adapting one of the examples is definitely the way to go. latency is much more controllable that way.
If you're calling play
on the main thread, try running it on a separate thread. What I ended up doing is:
#include <dispatch/dispatch.h> dispatch_queue_t playQueue = dispatch_queue_create("com.example.playqueue", NULL); AVAudioPlayer* player = ... dispatch_async(playQueue, ^{ [player play]; });
which fixed the worst of the framerate stuttering I was experiencing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With