Michel Michel - 9 months ago 83
Swift Question

How to play a sound in Swift 2 and 3?

I would like to play a sound in

Swift 2
Swift 3
as simple as possible.

My code worked in
Swift 1.0
but now it doesn't work anymore. I tried this code to play music in

override func viewDidLoad() {
let bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("Squart-MainMenu", withExtension: "mp3")!
do { bgMusic = try AVAudioPlayer(contentsOfURL: bgMusicURL, fileTypeHint: nil) }
catch _{
return print("no music file")
bgMusic.numberOfLoops = 1

if (Data.backgroundMenuPlayed == 0){
Data.backgroundMenuPlayed = 1


It throws always the error "NO AUDIO PLAYER" and the music file is in the main folder so I don't think that the music path isn't reachable.


Most preferably you might want to use AVFoundation. It provides all the essentials for working with audiovisual media.

Update: Compatible with Swift 2 and Swift 3 as suggested by some of you in the comments.

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
    let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!

    do {
        player = try AVAudioPlayer(contentsOfURL: url)
        guard let player = player else { return }

    } catch let error as NSError {

Make sure to change the name of your tune as well as the extension. The file needs to be properly imported (Project Build Phases > Copy Bundle Resources).