NEW: Master Swift design patterns with my latest book! >>

How to play sounds using AVAudioPlayer

Written by Paul Hudson    @twostraws

The most common way to play a sound on iOS is using AVAudioPlayer, and it's popular for a reason: it's easy to use, you can stop it whenever you want, and you can adjust its volume as often as you need. The only real catch is that you must store your player as a property or other variable that won't get destroyed straight away – if you don't, the sound will stop immediately.

AVAudioPlayer is part of the AVFoundation framework, so you'll need to import that:

import AVFoundation

Like I said, you need to store your audio player as a property somewhere so it is retained while the sound is playing. In our example we're going to play a bomb explosion sound, so I created a property for it like this:

var bombSoundEffect: AVAudioPlayer?

With those two lines of code inserted, all you need to do is play your audio file. This is done first by finding where the sound is in your project using path(forResource:), then creating a file URL out of it. That can then get passed to AVAudioPlayer to create an audio player object, at which point – finally – you can play the sound. Here's the code:

let path = Bundle.main.path(forResource: "example.mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)

do {
    bombSoundEffect = try AVAudioPlayer(contentsOf: url)
} catch {
    // couldn't load file :(

If you want to stop the sound, you should use its stop() method.

Available from iOS 2.2 – see Hacking with Swift tutorial 17

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Master iOS 11 now!

My book Practical iOS 11 gives you seven complete coding projects that teach all the major new features in iOS 11 in a smart, practical way.

Click here to visit the Hacking with Swift store >>