How to record Audio using AudioRecorder in iOS Swift

By | February 10, 2017

Well, its really easy for recording audio in an iOS application.

We will decalre two variables in our View Controller


var recordingSession: AVAudioSession!
var audioRecorder: AVAudioRecorder!

Request Permisson from the User


recordingSession = AVAudioSession.sharedInstance()

do {
    try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
    try recordingSession.setActive(true)
    recordingSession.requestRecordPermission() { [unowned self] allowed in
        DispatchQueue.main.async {
            if allowed {
                self.loadRecordingUI()
            } else {
                // failed to record!
            }
        }
    }
} catch {
    // failed to record!
}

Start Recording


func startRecording() {
    let audioFilename = getDocumentsDirectory()
                        .appendingPathComponent("my_recording.m4a")

    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    do {
        audioRecorder = try AVAudioRecorder(
              url: audioFilename, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record()
    } catch {
        finishRecording(success: false)
    }
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: 
                       .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

Set Delegate


class ViewController: UIViewController, AVAudioRecorderDelegate

Finish Recording

func finishRecording(success: Bool) {
    audioRecorder.stop()
    audioRecorder = nil

    if success {
        // recording finished
    } else {
        // recording failed
    }
}

Note :

Sometimes iOS Stops the recording when a phone call comes.
In that case we need to handle this. Since the delegate is our viewcontroller we can handle this using the delegate function audioRecorderDidFinishRecording

func audioRecorderDidFinishRecording(
     _ recorder: AVAudioRecorder, successfully flag: Bool) {
    if !flag {
        finishRecording(success: false)
    }
}

Send your comments to coderzheaven@gmail.com

Leave a Reply

Your email address will not be published. Required fields are marked *