YJ Choi YJ Choi - 3 months ago 23
iOS Question

AVAudioPlayer Not Working upon SpriteKit Scene Loading

I was struggling hardcore with a simple task: Play an audio file in the background when a SpriteKit scene loads.

I copied an audio file named "Test Song.wav" into my project and it was also found in my assets when I look under "Build Phases" > "Copy Bundle Resources" (which was what this post suggested to check for)

My code compiled just fine, and my ring/silent switch was correctly turned to ring, but the audio didn't play when the scene loaded.

I'm using


  • Xcode Version 8.0 beta

  • iPhone 6S Plus running iOS 10 Beta 1



Here was my broken code:

import AVFoundation

class GameScene: SKScene {

override func didMove(to view: SKView) {

if let path = Bundle.main().pathForResource("Test Song", ofType: "wav") {

let filePath = NSURL(fileURLWithPath:path)

let songPlayer = try! AVAudioPlayer.init(contentsOf: filePath as URL)

songPlayer.numberOfLoops = 0

songPlayer.prepareToPlay()

songPlayer.play()

}
}
}


Note: I learned that in Swift 3.0, AVAudioPlayer's init() method no longer accepted the NSError parameter, so this code DOES NOT compile:

var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)

Answer

Thanks to this website I learned that my problem was the scope of my AVAudioPlayer object.

Here is the working code:

class GameScene: SKScene {

    var songPlayer:AVAudioPlayer?

    override func didMove(to view: SKView) {

        if let path = Bundle.main().pathForResource("Test Song", ofType: "wav") {

            let filePath = NSURL(fileURLWithPath:path)

            songPlayer = try! AVAudioPlayer.init(contentsOf: filePath as URL)

            songPlayer?.numberOfLoops = 0 //This line is not required if you want continuous looping music

            songPlayer?.prepareToPlay()

            songPlayer?.play()

        }
    }
}