0

尝试使用计时器功能触发声音文件,但在计时器计数达到触发音频文件后,我收到此错误:
致命错误:在展开可选值时意外发现 nil。

我找不到与 nil/optionals 相关的问题。请帮帮我,谢谢。(A.wav 文件在项目资源文件夹中)

@State var timeCapture = 0
@State var counterValueInput = 0
@State var keySound: AVAudioPlayer?

var body: some View {TextField("Enter time", value: $counterValueInput, formatter: NumberFormatter())  Button(action: { self.timerBox()
            }) {Text("Start")
            }}
 func timerBox(){
    var runCount = 0
    var counterValue = 0
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
        print("\(runCount)")
        runCount += 1
        self.timeCapture = runCount
        counterValue = self.counterValueInput
        if runCount == counterValue {
            timer.invalidate()
            self.keySoundPlay()
        }
    }
}
 func keySoundPlay(){
    let path = Bundle.main.path(forResource: "A", ofType:"wav")!
    let url = URL(fileURLWithPath: path)
    do {keySound = try AVAudioPlayer(contentsOf: url)
        keySound?.play()
    } catch {
        print("nothing to catch")
    }
}
4

0 回答 0