在我的应用程序中,每次按下表格视图中的不同单元格时,我都想播放不同的音频文件。下面是我的实现,但我一直收到错误:
由于未捕获的异常“com.apple.coreaudio.avfaudio”而终止应用程序,原因:“所需条件为假:!nodeimpl->HasEngineImpl()”
我认为这个错误意味着它正在崩溃,因为音频引擎已经包含该节点。但我不确定如何在我的情况下解决它。
var audioPlayerFile : AVAudioFile!
var audioEngine = AVAudioEngine()
var pitchPlayer = AVAudioPlayerNode()
var timePitch = AVAudioUnitTimePitch()
var delay = AVAudioUnitDelay()
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
pitchPlayer.stop()
audioEngine.stop()
audioEngine.reset()
let filePathResource = myConversation.conversation[indexPath.row].fileName
print("file:", filePathResource)
if (filePathResource != nil) {
setUpAudioFilePath(filePathRes: filePathResource!)
}
timePitch.pitch = 0
delay.delayTime = 0
//append more effect:
audioEngine.connect(pitchPlayer, to: timePitch, format: audioPlayerFile.processingFormat)
audioEngine.connect(timePitch, to: delay, format: audioPlayerFile.processingFormat)
audioEngine.connect(delay, to: audioEngine.outputNode, format: audioPlayerFile.processingFormat)
pitchPlayer.scheduleFile(audioPlayerFile, at: nil, completionHandler: nil)
do { try audioEngine.start()}
catch {
print("Error: Starting Audio Engine")
}
pitchPlayer.play()
}
func setUpAudioFilePath (filePathRes: String) {
if let filePath = Bundle.main.path(forResource: filePathRes, ofType: "m4a") {
let filePathUrl = NSURL.fileURL(withPath: filePath)
do { audioPlayerFile = try AVAudioFile(forReading: filePathUrl) }
catch {
print("Error: Reading Audio Player File")
}
audioEngine.attach(pitchPlayer)
audioEngine.attach(timePitch)
audioEngine.attach(delay)
} else {
print("Error: filePath is empty")
}
}