Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From UnsafePointer<UnsafePointer<CFloat>> to an array of floats in Swift?

I'm trying to access AVAudioPCMBuffer.floatChannelData using Swift but it is of type UnsafePointer<UnsafePointer<CFloat>> (in Objective-C, @property(nonatomic, readonly) float *const *floatChannelData) and any attempt I make to access it results in execution failed.

Sample code to set-up a quick AVAudioPCMBuffer in a Swift Playground is included in a previous question:

Getting AVAudioPCMBuffer working (AVAudioFile.mm error code -50)

like image 660
Matthew Avatar asked Jun 06 '14 20:06

Matthew


2 Answers

Does this work?

let channels = UnsafeBufferPointer(start: myAudioBuffer.floatChannelData, count: Int(myAudioBuffer.format.channelCount))
let floats = UnsafeBufferPointer(start: channels[0], count: Int(myAudioBuffer.frameLength))
like image 200
trilorez Avatar answered Oct 21 '22 22:10

trilorez


What you can also do is in order to access AVAudioBuffer:

for var i = 0; i < Int(audioBuffer.frameLength); i+=Int(audioMixerNode.outputFormatForBus(0).channelCount) {
    self.audioBuffer.floatChannelData.memory[i] = 0.0f; // or whatever
}

You can find more about that in the Apple pre-release documentation:

The floatChannelData property returns pointers to the buffer’s audio samples, if the buffer’s format is 32-bit float. It returns nil if it is another format. The returned pointer is to format.channelCount pointers to float. Each of these pointers is to frameLength valid samples, which are spaced by stride samples.

like image 30
Michael Dorner Avatar answered Oct 21 '22 22:10

Michael Dorner