【问题标题】:AVFoundation: Malformed .m4a file format using AVAudioEngine and AVAudioFileAVFoundation:使用 AVAudioEngine 和 AVAudioFile 的格式错误的 .m4a 文件格式
【发布时间】:2014-08-15 14:23:34
【问题描述】:

我在使用 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)
}

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

【问题讨论】:

  • ID 为 17495706 的错误已提交给 Apple。
  • 您是否更改了设置以将 kAudioFormatAppleLossless 用于 AVFormatIDKey?
  • 你有没有设法解决这个问题?我有同样的问题。使用 .acc 可以正常工作,但 .m4a 不行

标签: swift avfoundation ios8 beta


【解决方案1】:

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

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

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

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

_recorder = AVAudioRecorder(URL: fileURL, settings: recsettings, error: &initRecorderError)   

【讨论】:

  • 不需要您的解决方法:您也可以从 swift 代码创建 NSNumber。例如像 [AVFormatIDKey : NSNumber(unsignedInt: kAudioFormatMPEG4AAC), AVNumberOfChannelsKey : NSNumber(unsignedInt:2), AVSampleRateKey : NSNumber(double:44100.0)] 对我来说很好。
  • 你不需要创建一个 AVAudioRecorder 来获取音频数据,他只需点击麦克风。
猜你喜欢
  • 2014-05-05
  • 2011-06-07
  • 2020-03-24
  • 2017-11-22
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
相关资源
最近更新 更多