我在iOS 8测试版中使用新的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)
}如果有人能在这方面提供一些意见,我会很高兴。谢谢!
发布于 2014-09-26 13:43:05
从XCode 6.0/Swift 1.0GM开始,我的Swift代码也不能记录为MPEG4AAC格式。显然,常量kAudioFormatMPEG4AAC的定义仍然不正确。该文件已创建,但未填充任何音频样本。
我能找到的唯一解决办法是在Objective C帮助函数中构建设置字典:
+ (NSDictionary *)getRecorderSettings
{
return @{AVFormatIDKey: @(kAudioFormatMPEG4AAC),
AVNumberOfChannelsKey: @(1),
AVSampleRateKey:@(22050),
AVEncoderAudioQualityKey: @(AVAudioQualityHigh)};
}并将其传递回用于初始化AVAudioRecorder的Swift代码:
_recorder = AVAudioRecorder(URL: fileURL, settings: recsettings, error: &initRecorderError) https://stackoverflow.com/questions/24401609
复制相似问题