Accessing Float samples of AVAudioPCMBuffer for processing
Asked Answered
S

1

6

I am trying to do some computation on the raw PCM samples of a mp3 files I'm playing with an AVAudioEngine graph. I have a closure every 44100 samples that provides an AVAudioPCMBuffer. It has a property channelData of type UnsafePointer<UnsafeMutablePointer<Float>>?. I have not worked with pointers in Swift 3 and so I'm unclear how to access these Float values.

I have the following code but there are many issues:

audioPlayerNode.installTap(onBus: 0, 
                           bufferSize: 1024, 
                           format: audioPlayerNode.outputFormat(forBus: 0)) { (pcmBuffer, time) in

let numChans = Int(pcmBuffer.format.channelCount)
let frameLength = pcmBuffer.frameLength
     
if let chans = pcmBuffer.floatChannelData?.pointee {
    for a in 0..<numChans {   
        let samples = chans[a]// samples is type Float.  should be pointer to Floats.
        for b in 0..<flength {
            print("sample: \(b)") // should be samples[b] but that gives error as "samples" is Float
        }
    }
}

For instance, how do I iterate through the UnsafeMutablePointer<Floats which are N float pointers where N is the number of channels in the buffer. I could not find discussion on accessing buffer samples in the Apple Docs on this Class.

I think the main problem is let samples = chans[a]. Xcode says chans is of type UnsafeMutablePointer<Float>. But that should be NumChannels worth of those pointers. Which is why I use a in 0..<numChans to subscript it. Yet I get just Float when I do.

EDIT:

hm, seems using chans.advanced(by: a) instead of subscripting fixed things

Suffering answered 10/3, 2017 at 16:9 Comment(1)
Firstly, check that if the numChans is 1Sempiternal
I
6

Here is what I've found:

let arraySize = Int(buffer.frameLength)
let samples = Array(UnsafeBufferPointer(start: buffer.floatChannelData![0], count:arraySize))

This is assuming buffer is the name of your AVAudioPCMBuffer.

This way you can avoid pointers, which is likely much simpler. Now you can actually search through the data using a for loop.

Irruption answered 3/5, 2017 at 4:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.