如何创建一个outputSettings Dictionary<String. Any> 与 AVAssetWriterInput 实例一起使用吗?

Pet*_*sby 1 avfoundation avassetwriter swift3 avassetwriterinput

我正在尝试将 MPMediaItem 实例转换为 caf 格式的音频文件。我一直在关注 Chris Adamson 的工作和他的帖子《从 iPod 库到 PCM 样本,步骤比以前少得多》

当我深入研究如何在 Swift 中做到这一点时,我发现了 Abel Domingues github FileConverter.swift在 Swift 中做到了这一点。

然后我开始转换为 Swift 3 作为协议的扩展。一切都很顺利,直到我尝试运行它。它在对象创建时崩溃assetWriterInput,似乎与outputSettings变量有关。

        var outputSettings = [
            AVFormatIDKey: kAudioFormatLinearPCM,
            AVSampleRateKey: 44100,
            AVNumberOfChannelsKey: 2,
            AVChannelLayoutKey: NSData(bytes:&channelLayout, length:MemoryLayout<AudioChannelLayout>.size),
            AVLinearPCMBitDepthKey: 16,
            AVLinearPCMIsNonInterleaved: false,
            AVLinearPCMIsFloatKey: false,
            AVLinearPCMIsBigEndianKey: false
        ] as [String : Any]

        // create an asset writer input
        let assetWriterInput = AVAssetWriterInput(mediaType:AVMediaTypeAudio, outputSettings:outputSettings as NSDictionary as! [String : Any])
Run Code Online (Sandbox Code Playgroud)

我收到的错误消息如下:

-[_SwiftValue unsignedIntValue]: unrecognized selector sent to instance 0x1704407b0 2016-10-13 18:34:52.032784 Testie[3098:1535938] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue unsignedIntValue]: unrecognized selector sent to instance 0x1704407b0'

我已经搜索了这方面的示例,但帖子必须是 Objective-C 和/或与设置视频词典相关的。

这是 AVAssetWriterInput 源中与音频相关的文档:

对于 AVMediaTypeAudio,outputSettings 字典当前不支持以下键:AVEncoderAudioQualityKey 和 AVSampleRateConverterAudioQualityKey。使用此初始化程序时,必须完全指定音频设置字典,这意味着它必须包含 AVFormatIDKey、AVSampleRateKey 和 AVNumberOfChannelsKey。如果没有其他可用的通道布局信息,则 AVNumberOfChannelsKey 的值为 1 将导致单声道输出,值为 2 将导致立体声输出。如果 AVNumberOfChannelsKey 指定的通道数大于 2,则字典还必须指定 AVChannelLayoutKey 的值。对于 kAudioFormatLinearPCM,必须包含所有相关的 AVLinearPCM*Key 键,对于 kAudioFormatAppleLossless,必须包含 AVEncoderBitDepthHintKey 键。请参阅 -initWithMediaType:outputSettings:sourceFormatHint: 了解避免为每个键指定值的方法。

那么字典中的什么导致了错误呢?

OOP*_*Per 5

在 Swift 3 中,kAudioFormatLinearPCM被导入为UInt32(又名),当放入 时,AudioFormatIDSwift 3.0.0 无法将其转换为适当的类型(在本例中) 。NSNumber[String: Any]

尝试这个:

    var outputSettings = [
        AVFormatIDKey: UInt(kAudioFormatLinearPCM),
        AVSampleRateKey: 44100,
        AVNumberOfChannelsKey: 2,
        AVChannelLayoutKey: NSData(bytes:&channelLayout, length:MemoryLayout<AudioChannelLayout>.size),
        AVLinearPCMBitDepthKey: 16,
        AVLinearPCMIsNonInterleaved: false,
        AVLinearPCMIsFloatKey: false,
        AVLinearPCMIsBigEndianKey: false
    ] as [String : Any]
Run Code Online (Sandbox Code Playgroud)

或者等到 Xcode 8.1/Swift 3.0.1,它应该可以解决你的问题。