我一直试图迅速使用Apple的CoreAudio。我发现了许多有关如何枚举设备上的流和通道的示例。但是,在调用UnsafeMutablePointer<AudioBufferList>.allocate()
时,它们似乎都使用了不正确的大小。
他们首先请求属性数据大小,该大小返回字节数。然后,他们使用此字节数来分配该大小的(不安全的)AudioBufferList
(使用字节数作为列表的大小!)。
[请在下面查看我的评论内联:
var address = AudioObjectPropertyAddress(
mSelector:AudioObjectPropertySelector(kAudioDevicePropertyStreamConfiguration),
mScope:AudioObjectPropertyScope(kAudioDevicePropertyScopeInput),
mElement:0)
var propsize = UInt32(0);
var result:OSStatus = AudioObjectGetPropertyDataSize(self.id, &address, 0, nil, &propsize);
if (result != 0) {
return false;
}
// ABOVE: propsize is set to number of bytes that property data contains, typical number are 8 (no streams), 24 (1 stream, 2 interleaved channels)
// BELOW: propsize is used for AudioBufferList capacity (in number of buffers!)
let bufferList = UnsafeMutablePointer<AudioBufferList>.allocate(capacity:Int(propsize))
result = AudioObjectGetPropertyData(self.id, &address, 0, nil, &propsize, bufferList);
if (result != 0) {
return false
}
let buffers = UnsafeMutableAudioBufferListPointer(bufferList)
for bufferNum in 0..<buffers.count {
if buffers[bufferNum].mNumberChannels > 0 {
return true
}
}
这一直有效,因为它分配的内存比UnsafeMutablePointer<AudioBufferList>
所需的要多得多,但这显然是错误的。
我一直在寻找一种从UnsafeMutablePointer<AudioBufferList>
返回的字节数中正确分配AudioObjectGetPropertyDataSize()
的方法,但是我整天都找不到任何东西。请帮助;)
从UnsafeMutablePointer<AudioBufferList>
返回的字节数正确分配AudioObjectGetPropertyDataSize()
您不应该分配UnsafeMutablePointer<AudioBufferList>
,而是分配确切大小的原始字节并将其转换为UnsafeMutablePointer<AudioBufferList>
。
类似这样的东西:
let propData = UnsafeMutableRawPointer.allocate(byteCount: Int(propsize), alignment: MemoryLayout<AudioBufferList>.alignment)
result = AudioObjectGetPropertyData(self.id, &address, 0, nil, &propsize, propData);
if (result != 0) {
return false
}
let bufferList = propData.assumingMemoryBound(to: AudioBufferList.self)