Play audio for UI sound effects

Water ripple
Sound feedback

Normally you need to play a simple UI sound effect as a feedback reaction to some user input or to notify the user about something happening. It’s a perfect case to use the AudioServices from AudioToolbox framework. It’s simple, straightforward, really easy to use and with 0 hassle doesn’t play any sound if the device is in silenced mode.

System Sound Services

There are three simple steps to play audio using AudioServices:

  1. Designate an audio file for playback by obtaining the SystemSoundID from System Sound server
  2. Play the sound by passing to System Sound server the designated SystemSoundID
  3. Dispose of any resources allocated to the playback for the provided SystemSoundID

As per documentation, the audio file must be packaged in a .caf, .aif, or .wav file, but I’ve found that since iOS 7 and up you can also use .mp3 packaging.

If you need to play the same sound frequently, save the SystemSoundID as you wish, pass nil to the completion block of AudioServicesPlaySystemSoundWithCompletion and dispose the resource in an appropriate place like view unload.

You can also take note of OSStatus returned by each function and if it’s different than kAudioServicesNoError look at AudioServices error codes to see whats happening.

Tip: even in silenced mode you can still play a vibration “sound” with AudioServicesPlaySystemSound(kSystemSoundID_Vibrate).

Limitations

But there are some drawbacks of AudioServices that can force you to look for another solution. It is limited to play sounds of a maximum duration of 30 seconds, there is no programmatic volume control, you can’t play more than one sound at a time and iOS has full control of what route the sound will take and if it will play at all.

Next time we explore how to gain power and control with the AVFoundation framework.