Swift 3 casting issue with UnsafeMutableRawPointer - AudioQueue

654 views Asked by At

I'm trying to convert to Swift 3 syntax the following code:

fileprivate func generateTone(_ buffer: AudioQueueBufferRef) {
        if noteAmplitude == 0 {
            memset(buffer.pointee.mAudioData, 0, Int(buffer.pointee.mAudioDataBytesCapacity))
        } else {
            let count: Int = Int(buffer.pointee.mAudioDataBytesCapacity) / MemoryLayout<Float32>.size
            var x: Double = 0
            var y: Double = 0
            let audioData = UnsafeMutablePointer<Float32>(buffer.pointee.mAudioData)

            for frame in 0..<count {
                x = noteFrame * noteFrequency / kSampleRate
                y = sin (x * 2.0 * M_PI) * noteAmplitude
                audioData[frame] = Float32(y)

                noteAmplitude -= noteDecay
                if noteAmplitude < 0.0 {
                    noteAmplitude = 0
                }

                noteFrame += 1
            }
        }

        buffer.pointee.mAudioDataByteSize = buffer.pointee.mAudioDataBytesCapacity
    }

I'm stuck with:

let audioData = UnsafeMutablePointer<Float32>(buffer.pointee.mAudioData)

Xcode complains:

Cannot invoke initializer for type 'UnsafeMutablePointer' with an argument list of type '(UnsafeMutableRawPointer)'

enter image description here

The project is available at here

Any help would be very appreciated :)

1

There are 1 answers

2
Martin R On BEST ANSWER

mAudioData is a "untyped pointer"(UnsafeMutableRawPointer), and you can convert it to a typed pointer with assumingMemoryBound:

let audioData = buffer.pointee.mAudioData.assumingMemoryBound(to: Float32.self)

See SE-0107 UnsafeRawPointer API for more information about raw pointers.