This tutorial assumes you know how to connect a UILabel to an @IBAction and add a sound file inside your Xcode project. The project setup is simple, there's a button on the screen and when you click the button it plays a lovely sound of birds chirping.
You can download The Sound of Birds for free.
Getting Started with AVAudioPlayer
import UIKit
import AVFoundation
class ViewController: UIViewController {
var soundPlayer: AVAudioPlayer!
func playSound(soundToPlay: String) {
if let url = Bundle.main.url(forResource: soundToPlay, withExtension: "mp3") {
do {
soundPlayer = try! AVAudioPlayer(contentsOf: url)
soundPlayer.play()
}
} else {
print("Error: Sound not found")
}
}
@IBAction func keyPressed(_ sender: UIButton) {
playSound(soundToPlay: sender.currentTitle!)
}
}
We begin by importing AVFoundation, a framework that you need to work with audiovisual assets.
class ViewController: UIViewController {
var soundPlayer: AVAudioPlayer!
Inside the ViewController class, we create a variable named soundPlayer of type AVAudioPlayer!, which is an implicitly unwrapped optional. This means the variable is expected to hold an AVAudioPlayer object, it's currently nil but will be assigned a value later.
func playSound(soundToPlay: String) {
if let url = Bundle.main.url(forResource: soundToPlay, withExtension: "mp3") {
do {
soundPlayer = try! AVAudioPlayer(contentsOf: url)
soundPlayer.play()
}
} else {
print("Error: Sound not found")
}
}
Then we create a function named playSound() that receives a parameter of type String. This parameter represents the name of the sound file we want to play, without the file extension.
Bundle.main.url(forResource: soundToPlay, withExtension: "mp3") searches for a file in the app's main bundle with the name specified by soundToPlay and the extension .mp3.
The if let statement is used to safely unwrap the optional URL returned by Bundle.main.url(forResource: soundToPlay, withExtension: "mp3").
If the file is found, url will hold the file's location, and the code inside the {} block is executed. If the file is not found (i.e., the URL is nil), the else block is executed.
The do { ... } block is used for error handling in Swift. It tries to execute the code inside the block, and if an error occurs, it's caught in the catch block. For this tutorial, I've omitted the catch block because I'm certain the sound file is present.
try AVAudioPlayer(contentsOf: url) tries to create an AVAudioPlayer instance using the sound file located at url. The try! keyword indicates that this line might throw an error.
If the AVAudioPlayer is successfully created, it's assigned to the soundPlayer variable
We then play the sound associated with the soundPlayer instance by calling the method .play().
@IBAction func keyPressed(_ sender: UIButton) {
playSound(soundToPlay: sender.currentTitle!)
}
Finally, we call playSound() inside keyPressed() so that every time we press the button, the lovely sound of birds chirping plays for us.
Although a simple tutorial, you've now acquired the skills to play sounds in your iOS apps using Swift's AVAudioPlayer. Leave a comment and let me know how you get on, or if you had any problems following this tutorial.
If you've enjoyed this article, subscribe and get an email as soon as I publish!