AVFoundation:使用 AVAudioEngine 和 AVAudioFile 的格式错误的 .m4a 文件

bor*_*rel 5 beta avfoundation swift ios8

我在使用 iOS 8 beta 中新的 AVFoundation 框架使用 AVAudioEngine 和 AVAudioFile 写入数据时遇到问题。

我想使用 m4a 格式在输入节点上点击来写入数据。但是,输出文件似乎已损坏,但使用完全相同的设置将文件格式更改为 .aac,文件格式正确并且可以成功播放:

import Foundation
import AVFoundation

func captureMicrophoneInput() {
    var error : NSError?

    var audioFileSettings = Dictionary<NSObject, AnyObject>()
    audioFileSettings[AVFormatIDKey]                 = kAudioFormatMPEG4AAC
    audioFileSettings[AVNumberOfChannelsKey]         = 1
    audioFileSettings[AVSampleRateKey]               = 44100.0
    audioFileSettings[AVEncoderBitRatePerChannelKey] = 16
    audioFileSettings[AVEncoderAudioQualityKey]      = AVAudioQuality.Medium.toRaw()

    let audioEngine = AVAudioEngine()
    let inputNode = audioEngine.inputNode

    // by using .acc the output file can be played successfully
    let url : CFURL = NSURL.fileURLWithPath("/path/to/outputdir/myFileWithProblematicExtension.m4a") as CFURL
    var audioFile = AVAudioFile(forWriting: url, settings: audioFileSettings, error: &error)

    if error != nil {
        println("AVAudioFile error")
        println(error)
        return
    }   

    // Write the output of the input node to disk
    inputNode.installTapOnBus(0, bufferSize: 4096, 
                                     format: inputNode.outputFormatForBus(0), 
                                      block: { (audioPCMBuffer : AVAudioPCMBuffer!, audioTime : AVAudioTime!) in
        audioFile.writeFromBuffer(audioPCMBuffer, error: &error)

        if error != nil {
            println("AVAudioFile error")
            println(error)
            return
        }
    })    

    audioEngine.startAndReturnError(&error)
}
Run Code Online (Sandbox Code Playgroud)

如果有人能对此提供一些意见,我会很高兴。谢谢!

小智 0

从 XCode 6.0/Swift 1.0 GM 开始,我的 Swift 代码也无法录制为 MPEG4AAC 格式。显然,常数 kAudioFormatMPEG4AAC 的定义仍然不正确。文件已创建,但未填充任何音频样本。

我能找到的唯一解决方法是在 Objective C 辅助函数中构建设置字典:

+ (NSDictionary *)getRecorderSettings
{
    return @{AVFormatIDKey: @(kAudioFormatMPEG4AAC),
             AVNumberOfChannelsKey: @(1),
             AVSampleRateKey:@(22050),
             AVEncoderAudioQualityKey: @(AVAudioQualityHigh)};
}
Run Code Online (Sandbox Code Playgroud)

并将其传递回 Swift 代码以初始化 AVAudioRecorder:

_recorder = AVAudioRecorder(URL: fileURL, settings: recsettings, error: &initRecorderError)   
Run Code Online (Sandbox Code Playgroud)