I'm working on an audio processing application using Swift and encountering an issue with AVAudioEngine when I try to detach an AVAudioPlayerNode. My application is a call simulator that plays audio files.
I've shared the relevant code snippets below.
Code for attaching and playing the node:
let audioFile = try AVAudioFile(forReading: fileURL)
let audioFormat = audioFile.processingFormat
let audioFrameCount = UInt32(audioFile.length)
let audioFileBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: audioFrameCount)!
try audioFile.read(into: audioFileBuffer)
if playerNode == nil {
playerNode = AVAudioPlayerNode()
audioEngine.attach(playerNode!)
// Use the stored outputNode for connection
if let outputNode = self.outputNode {
audioEngine.connect(playerNode!, to: outputNode, format: audioFormat)
} else {
print("Output node is not initialized")
return
}
}
// Start the engine if it's not running
if !audioEngine.isRunning {
try audioEngine.start()
}
// Schedule the buffer and play
playerNode?.scheduleBuffer(audioFileBuffer, at: nil, options: []/* .loops*/, completionHandler: nil)
playerNode?.play()
Code for ending the call and detaching the node:
if let playerNode = playerNode, audioEngine.isRunning {
playerNode.stop()
if audioEngine.attachedNodes.contains(playerNode), !playerNode.isPlaying {
print("[endcall debug] list of nodes: \(audioEngine.attachedNodes)")
audioEngine.detach(playerNode)
} else {
print("[endcall] node is busy")
return
}
}
However, when I try to detach the playerNode, the application crashes with the following error:
2023-11-17 14:20:17.372029+0100 CallSimulator[99266:3421546] [avae] AVAEInternal.h:76 required condition is false: [AVAudioEngineGraph.mm:1771:RemoveNode: ((graphNode->IsNodeState(kAUGraphNodeState_InInputChain) || graphNode->IsNodeState(kAUGraphNodeState_InOutputChain)))] 2023-11-17 14:20:17.418217+0100 CallSimulator[99266:3421546] *** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: (graphNode->IsNodeState(kAUGraphNodeState_InInputChain) || graphNode->IsNodeState(kAUGraphNodeState_InOutputChain))'
I am unsure why this error occurs when detaching the node. Here's what I'm trying to understand and fix:
- What could be causing this error when I try to detach the playerNode?
- Is there a specific procedure I need to follow before detaching a node from AVAudioEngine?
- Any suggestions or guidance on how to resolve or avoid this error would be greatly appreciated. Thank you for your help!