I already found an example code to recording with AVAudioEngine & success to output sampleRate 22050 aac format audioFile.
After I review the code, there is a problem that I have to setCategory AVAudioSessionCategoryPlayAndRecord instead of AVAudioSessionCategoryRecord.
How to improve the code for using "AVAudioSessionCategoryRecord" without "PlayAndRecord"?
(In this case I should use "AVAudioSessionCategoryRecord", right?)
If I setCategory to AVAudioSessionCategoryRecord, I get an ERROR:
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)'
There is an example about using microphone in AVAudioSessionCategoryRecord, it seems to me that we can record only with inputNode. https://developer.apple.com/library/prerelease/content/samplecode/SpeakToMe/Introduction/Intro.html
The following is code can work now.
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()
}
}
Related link