我在swifui中使用核心触觉向触觉反馈添加音频时遇到问题。系统在范围内不断显示错误“找不到音频ID”,因为 * 音频ID * 应为CHHapticEngine的函数registerAudioresource创建的注册音频资源ID参数。
下面是我编写的两个函数:
//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")}
}
我试过不同的方法,但都没有效果。任何想法或帮助将非常感谢!
编辑2这是我的代码的完整版本。虽然没有收到错误,但没有收到反馈。
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)")
}
}
}
1条答案
按热度按时间dz6r00yl1#
问题就在这里:
当您稍后尝试使用
audioID
时,它超出了作用域。您可以通过将audioID
的声明移到do/catch
之前来修复它:请注意,如果
registerAudioResource
失败,我添加了return
我还将
let engine
添加到了您的防护中,因为如果它是nil
,则没有任何意义