UnsafeMutablePointer<Float> 到 UnsafeMutablePointer<_>

UnsafeMutablePointer<Float> to UnsafeMutablePointer<_>

我真的被一个愚蠢但看似简单的问题弄疯了... 我必须将 Data 转换为 AVAudioPCMBuffer

好像很简单,但是随着Swift一切都变了 3.这种不断变化的诅咒语言(抱歉爆发)!

我有这段代码

let audioBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat!, frameCapacity: UInt32(data.count)/(audioFormat?.streamDescription.pointee.mBytesPerFrame)!)
audioBuffer.frameLength = audioBuffer.frameCapacity
let channels = UnsafeBufferPointer(start: audioBuffer.floatChannelData, count: Int(audioFormat!.channelCount))
data.copyBytes(to: UnsafeMutablePointer<Float>(channels[0]))

但是最后一行给我这个错误:

Cannot convert value of type 'UnsafeMutablePointer<Float>' to expected 
argument type 'UnsafeMutablePointer<_>'

有人可以解决这个问题吗?

检查 API Reference of Data,你可以找到 copyBytes 的 3 个重载:

func copyBytes(to: UnsafeMutablePointer<UInt8>, count: Int)

func copyBytes(to: UnsafeMutablePointer<UInt8>, from: Range<Data.Index>)

func copyBytes<DestinationType>(to: UnsafeMutableBufferPointer<DestinationType>, from: Range<Data.Index>?)

None 其中 UnsafeMutablePointer<Float> 作为其 to: 参数。

(在您的代码中,channels[0] 的类型变为 UnsafeMutablePointer<Float>,将其传递给 UnsafeMutablePointer<Float> 的初始化程序是 "do nothing"。)

如果你想调用第三个copyBytes,你需要创建一个UnsafeMutableBufferPointer<DestinationType>,在你的情况下DestinationType应该是Float

_ = data.copyBytes(to: UnsafeMutableBufferPointer(start: channels[0], count: Int(audioBuffer.frameLength)))

from: 参数在此 copyBytes 中是可选的,如果不放置 _ =,Swift 会抱怨未使用结果。)

如果您想使用 copyBytes 的其他重载,您可能需要将 UnsafeMutablePointer<Float> 转换为 UnsafeMutablePointer<UInt8>。您可以在 SO 的其他一些文章中找到如何执行此操作。请记住 count:from:(第二个)不是可选的。