为什么按下按钮时无法播放声音?

Why can't I play sound when a button is pressed?

这是我编写的代码,但我还不了解如何修复此错误。每次我 运行 应用程序构建成功,但是当我点击 button/key 时,它给我这个错误。

线程 1:致命错误:在展开可选值时意外发现 nil

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func keyAPressed(_ sender: UIButton) {
        playSound()
    }
    func playSound() {
        let url = Bundle.main.url(forResource: "C", withExtension: "wav")
        player = try! AVAudioPlayer (contentsOf: url!)
        player.play()
    }

}

您收到错误消息是因为 url 不存在。

检查您是否指定了正确的文件名并将播放函数包装在 do 块中以捕获任何其他错误。以下代码没有任何错误。

func playSound() {
    guard let url = Bundle.main.url(forResource: "C", withExtension: "wav") else {
        print("File not found")
        return
    }
    do {
        player = try AVAudioPlayer(contentsOf: url)
        player.play()
    } catch {
        print(error)
    }
    
}