我想知道如何创建 [String:AnyObject]
的字典来自 UnsafePointer<AudioStreamBasicDescription>
我想我不明白如何使用 UnsafePointer<T>
在Swift
.这是我的起点 - AVAudioFile
类有一个 fileFormat
AVAudioFormat
的属性(property)类型。 AVAudioFormat
有一个 streamDescription
返回 UnsafePointer<AudioStreamBasicDescription>
的属性作为只读属性。
我想看看这个结构中的值是什么,转换成字典似乎是一个合理的目标。事实上,AVAudioFormat
上似乎已经有一个“设置”属性。执行此操作的类,但我有兴趣了解访问存储在 UnsafePointer
中的值的“正确方法”我自己。
来自文档
Discussion: Returns the AudioStreamBasicDescription (ASBD) struct, for use with lower-level audio APIs
https://developer.apple.com/library/prerelease/ios/documentation/AVFoundation/Reference/AVAudioFormat_Class/index.html
有没有办法在检查结构是否不为 nil 后进行不安全转换?我会在这里使用 unsafeBitCast 吗?我很犹豫是否要过多地参与其中,因为我读到它“极其危险”...
我意识到我可以通过以下方式访问底层内存:
let audioFileURL:NSURL = NSBundle.mainBundle().URLForResource("FILENAME", with Extension: "mp3")
var file:AVAudioFile?
do {
file = try AVAudioFile(forReading: audioFileURL)
guard let file = file else {
fatalError("file must not be nil")
}
}catch {
print(error)
}
let format = file.processingFormat
let asbd:AudioStreamBasicDescription = format.streamDescription.memory
这很危险吗?我是否需要在创建 asbd 常量后出于某种原因解除分配?
我试着跟随这里的帖子 http://sitepoint.com/using-legacy-c-apis-swift但我只是不明白...在这里寻找有关最佳实践的任何方向。
更新:
做更多的研究,似乎可以使用基于这篇文章的反射来创建字典:http://freecake.angelodipaolo.org/simple-reflection-in-swift/
这是我目前所拥有的:
let asbdMirror = reflect(asbd)
var asbdDict = [String: Any]()
for i in 0..<asbdMirror.count {
let (propertyName, childMirror) = asbdMirror[i]
asbdDict[propertyName] = childMirror.value
}
为什么这是个坏主意?
最佳答案
您所做的一切都是正确的,您可以使用 asbd.mSampleRate
等访问描述中的所有值。将其转换为字典是没有意义的,因为事实并非如此,值没有键。
在使用这样的指针时,您也不必释放任何东西,除非您自己分配一个指针(当使用 malloc
或 alloc
时)
关于ios - 将 Swift UnsafePointer<AudioStreamBasicDescription> 转换为字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31439906/