Swift
Sound Programming
iOS Development
Audio Playback
SwiftUI

How to play a sound using Swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

For simple sound playback in an iPhone or iPad app, AVAudioPlayer is usually the right starting point. It works well for sound effects and local audio files, and the main thing to get right is resource loading plus keeping the player alive long enough to finish playback.

Use AVAudioPlayer for Local Sounds

The AVFoundation framework provides AVAudioPlayer, which is designed for audio files bundled with the app or stored locally on the device. A small helper object keeps the setup clean:

swift
1import AVFoundation
2
3final class AudioController: ObservableObject {
4    private var player: AVAudioPlayer?
5
6    func playSound(named name: String, extension ext: String = "wav") {
7        guard let url = Bundle.main.url(forResource: name, withExtension: ext) else {
8            print("Missing sound file: \(name).\(ext)")
9            return
10        }
11
12        do {
13            let session = AVAudioSession.sharedInstance()
14            try session.setCategory(.ambient, mode: .default)
15            try session.setActive(true)
16
17            player = try AVAudioPlayer(contentsOf: url)
18            player?.prepareToPlay()
19            player?.play()
20        } catch {
21            print("Audio playback failed: \(error)")
22        }
23    }
24}

The player property must be stored on the object, not inside a local function variable. If the player is created inside a short-lived method and never retained, playback may stop immediately because the object gets deallocated.

Trigger Playback from SwiftUI

Here is a minimal SwiftUI view that uses the controller:

swift
1import SwiftUI
2
3struct ContentView: View {
4    @StateObject private var audio = AudioController()
5
6    var body: some View {
7        Button("Play Sound") {
8            audio.playSound(named: "ding", extension: "mp3")
9        }
10        .padding()
11    }
12}

Add ding.mp3 or another supported audio file to your Xcode project and make sure it is included in the app target. Once the button is tapped, the bundled file plays through AVAudioPlayer.

Choose the Audio Session Category Deliberately

The audio session controls how your app behaves alongside system audio and the mute switch. In the sample above, .ambient is a reasonable default for lightweight sound effects because it mixes politely with other audio and respects silent mode.

If your app must continue playing audio even when the device is muted, you may need .playback instead:

swift
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playback, mode: .default)
try session.setActive(true)

That behavior change is significant, so do not set .playback casually. Pick the category that matches the user expectation of your app.

When AVPlayer Is a Better Fit

AVAudioPlayer is great for local files and short sounds. If you need streaming audio, remote URLs, or more advanced media playback behavior, AVPlayer may be a better choice. For the basic question “How do I play a sound bundled with my app?”, though, AVAudioPlayer stays the simplest answer.

A minimal AVPlayer example for a remote URL looks like this:

swift
1import AVFoundation
2
3let url = URL(string: "https://example.com/audio.mp3")!
4let player = AVPlayer(url: url)
5player.play()

That is useful for media apps, but it is usually more setup than you need for tap sounds or game effects.

Supported File Types

Common supported formats include .wav, .mp3, .m4a, and .aac, depending on platform capabilities. If playback fails, verify both the file type and the actual file contents. A file with an .mp3 suffix is not guaranteed to contain valid MP3 data.

When troubleshooting, first check whether the file exists in the app bundle:

swift
if let path = Bundle.main.path(forResource: "ding", ofType: "mp3") {
    print(path)
}

If that lookup returns nil, the code is not the problem. The resource is simply not packaged where the app expects it.

Common Pitfalls

The most common mistake is declaring AVAudioPlayer inside a function and not retaining it. The sound may start and then stop immediately because the object is released.

Another pitfall is forgetting target membership in Xcode. A file can appear in the project navigator and still not be copied into the app bundle.

It is also easy to choose the wrong audio session category. If the device is muted and you are using .ambient, the app is behaving correctly even though you do not hear anything.

Finally, the iOS Simulator is not always a perfect test environment for audio behavior. If sound is still unreliable after checking the basics, test on a real device.

Summary

  • 'AVAudioPlayer is the simplest way to play bundled local audio in Swift.'
  • Keep the player in a property so it stays alive for the duration of playback.
  • Load the file from Bundle.main and verify the resource is included in the app target.
  • Choose an audio session category that matches the intended app behavior.
  • Use AVPlayer instead when you need streaming or remote media playback.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.