I have a problem when adding audio to haptic feedback using core haptics in swifui. The system keeps showing the error "can't find audioID" in scope as audioID should be a registered audio resource ID parameter created by the function registerAudioresource of CHHapticEngine.
Here are the two functions that I have written:
//get engine ready
func prepareHaptics() {
guard CHHapticEngine.capablitiesForHardware().supportHaptics else { return }
do {
engine = try CHHapticEngine()
try engine?.start()
} catch {
print(“There was an error creating the engine: \(error.localizedDescription)”)
}
}
//play haptic and audio pattern
func Haptictransient() {
guard CHHapticEngine.capablitiesForHardware().supportHaptics else { return }
guard let sound = Bundle.main.url(forResource: "tapsound", withExtension: "wav") else { return }
do {
let audioID = try engine?.registerAudioresource(sound)
} catch {
print("Couldn't create the audio ID")
}
var events = [CHHapticEvent]()
//The code below get me an error "cannot find 'audioID' in scope"
let audio = CHHapticEvent(audioresourceID: audioID, parameters: [], relativeTime: 0)
events.append(audio)
let haptic = CHHapticEvent(evnetType: .hapticTransient, parameters: [], relativeTime: 0)
events.append(haptic)
do {
let pattern = try CHHapticPattern(events: evnets, parameters: [])
let player = try engine?.makePlayer(with: pattern)
try player?.start(atTime: 0)
} catch { print("Failed to play pattern")}
}
I tried different ways but none have worked. Any idea or help will be much appreciated!
Edit 2 This is the full version of my codes. Although no error received, no feedback received.
import SwiftUI
import CoreHaptics
struct TapView: View {
@State var engine: CHHapticEngine?
var body: some View {
Button(action: {
prepareHaptics()
hapticTransient()
}) { Text("PRESS") }
}
//get haptic engine ready
func prepareHaptics() {
guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else { return }
do {
engine = try CHHapticEngine()
try engine?.start()
} catch {
print("There was an error creating the engine: \(error.localizedDescription)")
}
}
//add haptic and audio feedback
func hapticTransient() {
guard CHHapticEngine.capabilitiesForHardware().supportsHaptics, let engine else { return }
guard let sound = Bundle.main.url(forResource: "tapsound", withExtension: "wav") else {return}
let audioID: CHHapticAudioREsourceID
do { audioID = try engine.registerAudioResource(sound) }
catch { print("Failed to create the audio") return }
var events = [CHHapticEvent]()
let audioEvent = CHHapticEvent(audioResourceID: audioID, parameters: [], relativeTime: 0)
let hapticEvent = CHHapticEvent(eventType: .hapticTransient, parameters: [], relativeTime: 0)
events.append(audioEvent)
events.append(hapticEvent)
do {
let pattern = try CHHapticPattern(events: events, parameter: [])
let player = try engine.makePlayer(with: pattern)
try palyer.start(atTime: 0)
} catch {
print("Failed to play pattern \(error.localDescription)")
}
}
}