Accessing AVAudioPCMBuffer - EXEC_BAD_ACCESS

I'm trying to access a AVAudioPCMBuffer.floatChannelData and getting a EXEC_BAD_ACCESS error when setting the frameLength above a certain value. I initially set frameLength to 16384 no problems there. I tried increasing it to 44100 - figuring this would make my buffer exactly 1 second long with a sampleRate of 44100. When going to lower values, I'm getting choppy audio from the buffer (not sure why, but one issue at a time i guess). The format of the Buffer should be UnsafePointer<UnsafeMutablePointer<Float>>. The floatChannelData should have the 'counts' of buffer[channels][frameLength].

buffer : AVAudioPCMBuffer
init(){
//set my format
let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatFloat32,
                                   sampleRate: 44100.0,
                                   channels: 1,
                                   interleaved: true)!

let frameLength = 44100
audioPlayerNode = AVAudioPlayerNode()
buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameLength)!

audioInputNode.installTap(onBus: 0, bufferSize:frameLength, format: format, block: {(buffer, time) in
            
            let channels = buffer.floatChannelData
            let floats = channels![0]

            for i in stride(from:0, to:Int(self.activeBuffer.frameLength), by: Int(self.audioMixerNode.outputFormat(forBus: 0).channelCount)){
                self.activeBuffer.floatChannelData![0][i] = floats[i] //get EXEC_BAD_ACCESS at index 17408
            }
        })
}```
1 Like

If you wrap your code block in triple backticks (`) then it formats it all as code.

ie:
```swift
// Hello World.
// This contains
// multiple lines
// formatted as swift code
```
becomes:

// Hello World.
// This contains
// multiple lines
// formatted as swift code

Thanks for that. Just changed it.

1 Like

This is not really the right forum for a question about AVFoundation (forums.developer.apple.com would be the right place), but I think the problem is your assumption about the bufferSize parameter to installTap. According to the documentation:

bufferSize
The requested size of the incoming buffers. The implementation may choose another size.

IIRC, 17000+ is what the implementation currently chooses.

BTW, is there a typo in your code? The property(?) represented by the first line is shown as buffer, but that is going to be shadowed by the buffer parameter inside the closure. Did you mean activeBuffer in the first line? That would also explain why your loop is trying to go to 44100 instead of the actual size of the passed-in buffer.

Thank you. My errors were ocurring at i = 17408. I thought I just didn't know what I was doing. I spent the better part of the day fumbling around with this.

That little annotation in the documentation isn't much of a help if "may" really means "will".