I want to record an audio file using AVAudioEngine. So it will be from the microphone to an output file. Later on I will add some effects. But for the moment, I just want to make it work.
Can anyone provide me with the steps or a sample code so that I can start?
In your . swift file create variable of type AVAudioSession, AVAudioRecorder, AVAudioPlayer to start recording session, recorder instance and to play recorded audio respectively.
An object that manages a graph of audio nodes, controls playback, and configures real-time rendering constraints.
Here's my simple solution. Output file will be in documents directory. Note, that i removed error handling for brevity.
var engine = AVAudioEngine()
var file: AVAudioFile?
var player = AVAudioPlayerNode() // if you need play record later
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
file = AVAudioFile(forWriting: URLFor("my_file.caf")!, settings: engine.inputNode.inputFormatForBus(0).settings, error: nil)
engine.attachNode(player)
engine.connect(player, to: engine.mainMixerNode, format: engine.mainMixerNode.outputFormatForBus(0)) //configure graph
engine.startAndReturnError(nil)
}
func record() {
engine.inputNode.installTap(onBus: 0, bufferSize: 1024, format: engine.mainMixerNode.outputFormat(forBus: 0)) { (buffer, time) -> Void in
try! self.file?.write(from: buffer)
return
}
}
@IBAction func stop(sender: AnyObject) {
engine.inputNode.removeTap(onBus: 0)
}
func URLFor(filename: String) -> NSURL? {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
return documentsDirectory.appendingPathComponent(filename)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With