gpt4 book ai didi

swift - 访问元素给定结构 UnsafeMutablePointer

转载 作者:行者123 更新时间:2023-11-28 14:59:28 32 4
gpt4 key购买 nike

在 C 中,我有以下代码来分配一个具有适当大小的 AudioBufferList,然后用相关数据填充它。

AudioObjectPropertyScope scope = mIsInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
AudioObjectPropertyAddress address = { kAudioDevicePropertyStreamConfiguration, scope, 0 };
UInt32 propertySize;
__Verify_noErr(
AudioObjectGetPropertyDataSize(mID, &address, 0, NULL, &propertySize)
);
AudioBufferList *bufferList = (AudioBufferList *) malloc(propertySize);
__Verify_noErr(
AudioObjectGetPropertyData(mID, &address, 0, NULL, &propertySize, bufferList)
);

然后,我可以访问结构元素:

UInt32 result { 0 };
for(UInt32 i = 0; i < bufferList->mNumberBuffers; ++i)
{
result += bufferList->mBuffers[i].mNumberChannels;
}
free(bufferList)

鉴于我使用相同的框架,即 AudioToolbox,我如何在 Swift 中复制此行为?

我尝试了以下方法,但无法访问 mNumberBuffers

let scope: AudioObjectPropertyScope = scope ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput
var address: AudioObjectPropertyAddress = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyStreamConfiguration, mScope: scope, mElement: 0)
var size: UInt32 = 0
CheckError(
AudioObjectGetPropertyDataSize(mID, &address, 0, nil, &size),
"Couldn't get stream configuration data size."
)
var bufferList = UnsafeMutableRawPointer.allocate(bytes: Int(size), alignedTo: MemoryLayout<AudioBufferList>.alignment).assumingMemoryBound(to: AudioBufferList.self)
CheckError(
AudioObjectGetPropertyData(mID, &address, 0, nil, &size, bufferList),
"Couldn't get device's stream configuration"
)

最佳答案

您可以像这样创建一个 AudioBufferList:

import AudioUnit
import AVFoundation

var myBufferList = AudioBufferList(
mNumberBuffers: 2,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(2),
mDataByteSize: 2048,
mData: nil) )

当传入一个缓冲区数量未知的 bufferList 时,您可以像这样获得缓冲区的数量和示例数据:

let myBufferListPtr = UnsafeMutableAudioBufferListPointer(myBufferList)
let numBuffers = myBufferListPtr.count
if (numBuffers > 0) {
let buffer : AudioBuffer = myBufferListPtr[0]
let bufferDataPointer = UnsafeMutableRawPointer(buffer.mData)
if let dataPtr = bufferDataPointer {
dataPtr.assumingMemoryBound(to: Float.self)[ i ] = x
...

我的源代码示例的其余部分在 GitHub 上:https://gist.github.com/hotpaw2/ba815fc23b5d642705f2b1dedfaf0107

关于swift - 访问元素给定结构 UnsafeMutablePointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49076625/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com