October 29, 2016

Playing short sounds in iOS with Swift 3

It was hard to find a concise example of playing a short audio sound in an iOS application using Swift 3. I write one such example here for posterity:


Import the AudioToolbox framework. Use the System Sound Services to play sounds that are 30 seconds or less in length.

import AudioToolbox

let filename = "mySoundFile"
let ext = "wav"

if let soundUrl = Bundle.main.url(forResource: filename, withExtension: ext) {
  var soundId: SystemSoundID = 0

  AudioServicesCreateSystemSoundID(soundUrl as CFURL, &soundId)

  AudioServicesAddSystemSoundCompletion(soundId, nil, nil, { (soundId, clientData) -> Void in
  }, nil)



The filename and ext variables represent the name and extension of the sound file we want to play.

The if let soundUrl... expression means that the block that plays the sound is executed only if the sound file exists and and accessible to the application.

The System Sound Services documentation recommends that we create a soundId for the sound that we want to play. We can do this with:

AudioServicesCreateSystemSoundID(CFURL, UnsafeMutablePointer<SystemSoundID>)

The sound played with AudioServicesPlaySystemSound(SystemSoundID).

After playing our sound, it is also recommended to dispose of the soundId. Create it again if we need to play the sound. We dispose of the sound by giving a callback function to AudioServicesAddSystemSoundCompletion(). The callback function is the closure:

{ (soundId, _) -> Void in

The callback function should have two parameters, though we don’t need the second parameter for this case (hence the _). TheAudioServicesDisposeSystemSoundID() function is provided by theAudioToolbox framework.


coffee with room for code, by Brian Mathiyakom 2016