Joe
Joe

Reputation: 353

Recording audio file using AVAudioEngine

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?

Upvotes: 12

Views: 9473

Answers (1)

rts
rts

Reputation: 379

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)
}

Upvotes: 9

Related Questions