Record an audio file using AVAudioEngine

I want to record an audio file using AVAudioEngine. This way it will be from the microphone to the output file. I will add some effects later. But for now, I just want to make it work.

Can someone provide me with steps or sample code so I can get started?

+4
source share
1 answer

Here is my simple solution. The output file will be in the document directory. Note that I have shortened 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)
}

@IBAction func record(sender: AnyObject) {
    engine.inputNode.installTapOnBus(0, bufferSize: 1024, format: engine.mainMixerNode.outputFormatForBus(0)) { (buffer, time) -> Void in
        self.file?.writeFromBuffer(buffer, error: nil)
        return
    }
}

@IBAction func stop(sender: AnyObject) {
    engine.inputNode.removeTapOnBus(0)
}


func URLFor(filename: String) -> NSURL? {
    if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
        let dir = dirs[0] //documents directory
        let path = dir.stringByAppendingPathComponent(filename)
        return NSURL(fileURLWithPath: path)
    }
    return nil
}
+3
source

All Articles