Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recording audio file using AVAudioEngine

Tags:

ios

swift

iphone

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?

like image 915
Joe Avatar asked Oct 15 '14 17:10

Joe


People also ask

How do I record audio in Swift?

In your . swift file create variable of type AVAudioSession, AVAudioRecorder, AVAudioPlayer to start recording session, recorder instance and to play recorded audio respectively.

What is Avaudioengine?

An object that manages a graph of audio nodes, controls playback, and configures real-time rendering constraints.


1 Answers

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)
}
like image 83
RomanTsopin Avatar answered Sep 23 '22 11:09

RomanTsopin