使用UnsafeMutableRawPointer的Swift 3转换问题 - AudioQueue

时间:2016-12-27 18:53:13

标签: swift casting swift3 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抱怨:

  

无法为类型&#39; UnsafeMutablePointer&#39;调用初始化程序。   使用类型&#39;(UnsafeMutableRawPointer)&#39;

的参数列表

enter image description here

该项目位于here

非常感谢任何帮助:)

1 个答案:

答案 0 :(得分:2)

mAudioData是一个“无类型指针”(UnsafeMutableRawPointer)和你 可以使用assumingMemoryBound将其转换为类型指针:

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

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