AVAudioPlayer 无法处理 SpriteKit 场景加载

AVAudioPlayer Not Working upon SpriteKit Scene Loading

我一直在努力完成一项简单的任务:加载 SpriteKit 场景时在后台播放音频文件。

我将一个名为 "Test Song.wav" 的音频文件复制到我的项目中,当我在 "Build Phases" > "Copy Bundle Resources" 下查看时,它也在我的资产中找到(这就是 this post 建议检查)

我的代码编译得很好,我的 ring/silent switch 正确地变成了响铃,但是当场景加载时音频没有播放。

我正在使用

这是我的错误代码:

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

        }
    }
}

注意:我了解到在Swift3.0中,AVAudioPlayer的init()方法不再接受NSError参数,所以这段代码编译:

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

感谢 this website 我了解到我的问题是我的 AVAudioPlayer 对象的范围。

这是工作代码:

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

        }
    }
}