Swift version: 5.6
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.
SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until October 1st.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 2.2 – see Hacking with Swift tutorial 17
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.