Swift UnsafeMutableRawPointer 的 3 个转换问题 - AudioQueue

Swift 3 casting issue with UnsafeMutableRawPointer - AudioQueue

我正在尝试将以下代码转换为 Swift 3 语法:

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
    }

我坚持:

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

Xcode抱怨:

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

该项目可在 here

任何帮助将不胜感激:)

mAudioData 是一个 "untyped pointer"(UnsafeMutableRawPointer),而你 可以使用 assumingMemoryBound:

将其转换为类型指针
let audioData = buffer.pointee.mAudioData.assumingMemoryBound(to: Float32.self)

SE-0107 UnsafeRawPointer API 有关原始指针的更多信息。