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:
AudioToolbox framework. Use the System Sound Services to play
sounds that are 30 seconds or less in length.
ext variables represent the name and extension of the sound
file we want to play.
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
for the sound that we want to play. We can do this with:
The sound played with
After playing our sound, it is also recommended to dispose of the
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:
The callback function should have two parameters, though we don’t
need the second parameter for this case (hence the
AudioServicesDisposeSystemSoundID() function is provided by