0

Trying to trigger a sound file with timer function, but after timer count reaching to trigger the audio file, I get this error:
Fatal error: Unexpectedly found nil while unwrapping an Optional value.

I can't find the problem related to the nil/optionals. Help me with that please, thanks. (The A.wav file is in the project resources folder)

@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")
    }
}
Bezi
  • 57
  • 1
  • 7
  • If the code crashes in the `path(forResource` line then the file is definitely **not** in the resources folder. By the way there is also `url(forRecource` – vadian Mar 27 '20 at 16:55
  • Yup, you were right. I checked the resources again, I don't know why, but once replace the existing file with a new file with same name, it works. Thanks for the hint. – Bezi Mar 27 '20 at 17:55

0 Answers0