我正在努力完成一项简单的任务:在加载SpriteKit场景时在后台播放音频文件。
我将名为“Test Song.wav”的音频文件复制到我的项目中,当我查看“Build Phases”>时,我的资产中也找到了它。 “复制捆绑资源”(这是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()
}
}
}
注意:我了解到在Swift 3.0中,AVAudioPlayer的init()方法不再接受NSError参数,因此此代码不会编译:
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
答案 0 :(得分:1)
感谢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()
}
}
}