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

How to play sounds using AVAudioPlayer

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)
    bombSoundEffect?.play()
} 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.

Swift on the server is here

Get ahead of the game and learn server-side Swift with my latest book – build real-world projects while you learn!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 1.0/5

Click here to visit the Hacking with Swift store >>