Creating and playing a sound in swift
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
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:
And a view controller that uses it:
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.
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:
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
AVAudioPlayerfor 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
AVAudioSessionwhen playback behavior needs to be explicit. - Test on a real device when mute switch and routing behavior matter.

