当我运行此功能时游戏崩溃?

时间:2016-12-09 00:33:23

标签: swift audio

每当玩家收集硬币时,它就是声音,但是一旦角色接触到硬币,游戏就会冻结并退出。

 func playTap() {
    if let url = Bundle.main.url(forResource: "tap", withExtension: "caf"){

        tap = try AVAudioPlayer(contentsOf: url)
        guard let tap = tap else { return }

        tap.prepareToPlay()
        tap.play()
} else {
    print(error.localizedDescription)
    }

}

1 个答案:

答案 0 :(得分:0)

我猜你的代码正在崩溃,因为你正在尝试 FORCE UNWRAP一个空的可选,并在行的末尾加上

let url = Bundle.main.url(forResource: "tap", withExtension: "caf")!

尝试

if let url = Bundle.main.url(forResource: "tap", withExtension: "caf"){
     //Code here
} else {
}

guard let url = Bundle.main.url(forResource: "tap", withExtension: "caf") else {}

修改

拼写检查键值!!