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")
}
}