我已經找到了一個示例代碼來錄製AVAudioEngine &成功輸出sampleRate 22050 aac格式的audioFile。使用AVAudioEngine,AVAudioSession setCategory AVAudioSessionCategoryRecord記錄並重新採樣aac格式?
我查看了代碼後,出現了一個問題,我必須設置類AVAudioSessionCategoryPlayAndRecord而不是AVAudioSessionCategoryRecord。
How to improve the code for using "AVAudioSessionCategoryRecord" without "PlayAndRecord"?
(在這種情況下,我應該使用 「AVAudioSessionCategoryRecord」 吧?)
如果我setCategory到AVAudioSessionCategoryRecord,我得到一個錯誤:
AVAudioEngineGraph.mm:1070: Initialize: required condition is false: IsFormatSampleRateAndChannelCountValid(outputHWFormat)
Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: 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()
}
}
關聯鏈接
How can I specify the format of AVAudioEngine Mic-Input?
Recording audio file using AVAudioEngine