Skip to content
DeveloperMemos

Playing a Sound With Swift Using AVFoundation

Swift, AVFoundation, Audio1 min read

Have you ever wanted to add sound to your iOS app to create a more immersive user experience? The AVFoundation framework in Swift allows you to easily play sounds in your app. In this tutorial, we'll walk through how to use AVFoundation to play a sound in your app.

Import AVFoundation

The first step is to import the AVFoundation framework. You can do this by adding the following import statement to the top of your Swift file:

1import AVFoundation

Setting up AVAudioPlayer

Next, we need to set up an instance of AVAudioPlayer. This is the class that we'll use to actually play the sound. Here's an example of how to set up an AVAudioPlayer instance:

1var audioPlayer: AVAudioPlayer?
2
3func setupAudioPlayer() {
4 guard let sound = Bundle.main.path(forResource: "sound", ofType: "mp3") else { return }
5 let url = URL(fileURLWithPath: sound)
6
7 do {
8 audioPlayer = try AVAudioPlayer(contentsOf: url)
9 audioPlayer?.prepareToPlay()
10 } catch {
11 print("Error loading sound file: \(error.localizedDescription)")
12 }
13}

In this example, we're loading a sound file called "sound.mp3" from the app's main bundle. You'll want to replace this with the name of the sound file that you want to play in your app. The prepareToPlay() method is called to prepare the AVAudioPlayer instance for playback.

Playing the Sound

Now that we have an AVAudioPlayer instance set up, we can play the sound by calling the play() method. Here's an example of how to play the sound when a button is tapped:

1@IBAction func playButtonTapped(_ sender: UIButton) {
2 audioPlayer?.play()
3}

In this example, we're calling the play() method on the audioPlayer instance when the "Play" button is tapped.

Pausing and Stopping the Sound

AVAudioPlayer also provides methods for pausing and stopping the playback of a sound. Here's an example of how to pause and stop the sound:

1@IBAction func pauseButtonTapped(_ sender: UIButton) {
2 audioPlayer?.pause()
3}
4
5@IBAction func stopButtonTapped(_ sender: UIButton) {
6 audioPlayer?.stop()
7 audioPlayer?.currentTime = 0
8}

In this example, we're calling the pause() method to pause the playback of the sound, and the stop() method to stop the playback of the sound. We're also resetting the playback time of the audioPlayer instance to 0 when the stop button is tapped.

Closing Thoughts

In this tutorial, we've learned how to use the AVFoundation framework in Swift to play sounds in your iOS application. We've covered setting up an instance of AVAudioPlayer, playing a sound, and pausing and stopping the sound. With these tools, you can easily add sound to your app to create a more immersive user experience.