1

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)
Community
  • 1
  • 1
YJ Choi
  • 157
  • 2
  • 8
  • 1
    Hello, I appreciate your moderation efforts, and you are technically correct that this is a duplicate. I'm not trying to argue: I'm genuinely curious how this site works. With that in mind: I can't help but wonder why my post can't stand on its own without being downvoted for not being useful. I made it a "Q&A" style post so nobody's time was wasted in needing/trying to answer it, it is written in Swift 3.0 and for iOS 10, and I cite all my sources. If I didn't know the post you linked to existed, how was I to know to contribute a comment to that post instead of making my own post? – YJ Choi Jun 25 '16 at 23:18

1 Answers1

1

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()

        }
    }
}
YJ Choi
  • 157
  • 2
  • 8