UnsafeMutablePointer <float>到UnsafeMutablePointer&lt; _&gt;

时间:2016-11-30 15:56:19

标签: swift swift3 unsafemutablepointer avaudiopcmbuffer

我真的为一个愚蠢而且显而易见的简单问题而疯狂...... 我必须将Data转换为AVAudioPCMBuffer

期待this question这似乎很容易,但是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<_>'

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

1 个答案:

答案 0 :(得分:1)

检查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>?)

他们都没有将UnsafeMutablePointer<Float>作为to:参数。

(在您的代码中,channels[0]的类型变为UnsafeMutablePointer<Float>,将其传递给初始化程序UnsafeMutablePointer<Float>是&#34;什么都不做&#34;。)

如果您想拨打第三个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:(在第二个中)不是可选的。