Ich habe bereits einen Beispielcode zum Aufzeichnen mit AVAudioEngine & gefunden, um sampleRate 22050 aac format audioFile auszugeben.Record und Resample zu aac Format mit AVAudioEngine, AVAudioSession setCategory AVAudioSessionCategoryRecord?
Nachdem ich den Code überprüft habe, gibt es ein Problem, dass ich Category AVAudioSessionCategoryPlayAndRecord anstelle von AVAudioSessionCategoryRecord festlegen muss.
How to improve the code for using "AVAudioSessionCategoryRecord" without "PlayAndRecord"?
(In diesem Fall sollte ich "AVAudioSessionCategoryRecord", nicht wahr?)
Wenn ich AVAudioSessionCategoryRecord setCategory, bekomme ich eine Fehlermeldung:
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)'
Es ist ein Beispiel über Mikrofon In AVAudioSessionCategoryRecord scheint es mir, dass wir nur mit inputNode aufnehmen können. https://developer.apple.com/library/prerelease/content/samplecode/SpeakToMe/Introduction/Intro.html
Der folgende Code kann jetzt funktionieren.
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
How can I specify the format of AVAudioEngine Mic-Input?
Recording audio file using AVAudioEngine