1

Usually people are asking for things to transform from Objective-C to Swift. I have to ask the other way round today.

Given the following line in Swift:

let values:[Float] = Array(UnsafeBufferPointer(start: buffer.floatChannelData?[0], count:Int(buffer.frameLength)))

Compiles successfully and I get an array of float values. Since floatChannelData on AVAudioPCMBuffer is defined as float * const I was assuming that the returning array of values is copied from the address floatChannelData[0] points to.

How would I achieve the same behaviour in Objective-C?

1 Answer 1

2

Depends on whether you want a C array of floats, or an NSArray.

(disclaimer: written in Chrome)

For a C array, we should be able to just copy the original values:

float *values = malloc(buffer.frameLength * sizeof(float)); // remember to free eventually
memcpy(values, buffer.floatChannelData[0], buffer.frameLength * sizeof(float));

For an NSArray we will have to wrap the floats in NSNumber objects:

NSMutableArray *values = [NSMutableArray new];

for (AVAudioFrameCount i = 0; i < buffer.frameLength; i++) {
    [values addObject:@(buffer.floatChannelData[0][i])];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for helping out. Compiler still not too happy Illegal type 'float *' used in a boxed expression.
My bad, misread your OP and didn't notice that floatChannelData was a float ** rather than a float *. I'll edit the answer.
That's the solution! Thanks! Nice to know about the AVAudioFrameCount typedef as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.