12

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?

Joe
  • 353
  • 5
  • 16

1 Answers1

8

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)
}
Eric
  • 16,003
  • 15
  • 87
  • 139
rts
  • 359
  • 4
  • 9
  • 5
    it crashes when I call the write to buffer function with this error : 'com.apple.coreaudio.avfaudio', reason: 'error -50' – user3703910 Mar 19 '17 at 12:53