我已经找到了使用AVAudioEngine& amp;成功输出sampleRate 22050 aac格式audioFile。
在我查看代码之后,有一个问题是我必须使用setCategory AVAudioSessionCategoryPlayAndRecord而不是AVAudioSessionCategoryRecord。
如何改进使用“AVAudioSessionCategoryRecord”的代码 “PlayAndRecord”?
(在这种情况下我应该使用“AVAudioSessionCategoryRecord”,对吧?)
如果我将setCategory设置为AVAudioSessionCategoryRecord,我会收到错误:
AVAudioEngineGraph.mm:1070:初始化:必需条件为false: IsFormatSampleRateAndChannelCountValid(outputHWFormat)
由于未捕获的异常而终止应用 'com.apple.coreaudio.avfaudio',原因:'所需条件为假: IsFormatSampleRateAndChannelCountValid(outputHWFormat)'
有一个关于在AVAudioSessionCategoryRecord中使用麦克风的例子,在我看来,我们只能用inputNode进行记录。 https://developer.apple.com/library/prerelease/content/samplecode/SpeakToMe/Introduction/Intro.html
以下代码现在可以正常工作。
import UIKit
import AVFoundation
class ViewController: UIViewController {
let audioEngine = AVAudioEngine()
lazy var inputNode : AVAudioInputNode = {
return self.audioEngine.inputNode!
}()
let sampleRate = Double(22050)
lazy var outputFormat : AVAudioFormat = {
return AVAudioFormat(commonFormat: self.inputNode.outputFormatForBus(0).commonFormat,
sampleRate: self.sampleRate,
channels: AVAudioChannelCount(1),
interleaved: false)
}()
let converterNode = AVAudioMixerNode()
lazy var aacFileURL : NSURL = {
let dirPath = NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let filePath = dirPath.URLByAppendingPathComponent("rec.aac")
return filePath
}()
lazy var outputAACFile : AVAudioFile = {
var settings = self.outputFormat.settings
settings[AVFormatIDKey] = NSNumber(unsignedInt: kAudioFormatMPEG4AAC)
return try! AVAudioFile(forWriting: self.aacFileURL,
settings:settings)
}()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try! audioSession.setActive(true)
self.audioEngine.attachNode(converterNode)
self.audioEngine.connect(inputNode,
to: converterNode,
format: inputNode.outputFormatForBus(0))
self.audioEngine.connect(converterNode,
to: self.audioEngine.mainMixerNode,
format: outputFormat)
converterNode.volume = 0
converterNode.installTapOnBus(0, bufferSize: 1024, format: converterNode.outputFormatForBus(0)) { (buffer, when) in
try! self.outputAACFile.writeFromBuffer(buffer)
}
try! self.audioEngine.start()
}
}
相关链接
答案 0 :(得分:0)
AVAudioMixerNode
无法在非压缩格式和压缩格式之间进行转换。为此,您需要AVAudioConverter
。