Swift
Sound Development
iOS Programming
Audio Playback
Mobile App Development

Creating and playing a sound in swift

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Playing a sound in Swift is usually simple if the sound file ships with your app. For local audio such as button clicks, spoken prompts, or a short loop, AVAudioPlayer from AVFoundation is the standard choice because it is small, reliable, and easy to control.

Add the Audio File to the App Bundle

Start by adding a file such as click.mp3 or success.wav to your Xcode project. Make sure the file is included in the app target. If it is missing from target membership, the code can build successfully but fail at runtime because the resource is not actually copied into the bundle.

It is also worth checking the exact file name and extension. click.mp3 and Click.mp3 are different resource names, so verify the spelling before debugging anything deeper.

Play a Local Sound with AVAudioPlayer

Here is a small reusable class:

swift
1import AVFoundation
2
3final class SoundPlayer {
4    private var player: AVAudioPlayer?
5
6    func playSound(named name: String, fileExtension: String) {
7        guard let url = Bundle.main.url(forResource: name, withExtension: fileExtension) else {
8            print("Missing resource: \(name).\(fileExtension)")
9            return
10        }
11
12        do {
13            player = try AVAudioPlayer(contentsOf: url)
14            player?.prepareToPlay()
15            player?.play()
16        } catch {
17            print("Playback failed: \(error)")
18        }
19    }
20}

And a view controller that uses it:

swift
1import UIKit
2
3final class ViewController: UIViewController {
4    private let soundPlayer = SoundPlayer()
5
6    @IBAction func playButtonTapped(_ sender: UIButton) {
7        soundPlayer.playSound(named: "click", fileExtension: "mp3")
8    }
9}

The stored player property is important. If you create the audio player as a local variable inside the method, it can be released too early and playback may stop immediately.

Configure the Audio Session

If audio behavior matters, configure AVAudioSession instead of relying on defaults. That is especially important when mute switch behavior or background playback matters.

swift
1import AVFoundation
2
3func activateAudioSession() {
4    let session = AVAudioSession.sharedInstance()
5
6    do {
7        try session.setCategory(.playback, mode: .default)
8        try session.setActive(true)
9    } catch {
10        print("Audio session error: \(error)")
11    }
12}

Call this during app setup before starting playback. .playback is a good default for app-owned media. If your app also records audio, a different category may be more appropriate.

Looping and Volume

AVAudioPlayer supports common controls directly:

swift
1player?.volume = 0.6
2player?.numberOfLoops = -1
3player?.currentTime = 0
4player?.play()

Setting numberOfLoops to -1 makes the sound repeat forever. That is useful for alarms or ambient audio. Use 0 to play once.

Common Pitfalls

One common problem is forgetting to keep a strong reference to AVAudioPlayer. When the object is deallocated, playback can stop.

Another issue is a missing resource in the app bundle. Always confirm that the sound file is part of the correct target and that the file name matches exactly.

Audio session configuration is another frequent source of confusion. If the app behaves differently on a real device than in the simulator, check whether the chosen category fits the intended behavior with the mute switch and other audio on the device.

Finally, test on physical hardware if sound is an important part of the app. Real device routing and interruption behavior are more representative than simulator output.

Summary

  • Use AVAudioPlayer for most bundled audio files in a Swift app.
  • Add the sound file to the app target so it ends up in Bundle.main.
  • Keep a strong reference to the player object while audio is playing.
  • Configure AVAudioSession when playback behavior needs to be explicit.
  • Test on a real device when mute switch and routing behavior matter.

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.