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 {
            } else {
                // failed to record!
} catch {
    // failed to record!

Start Recording

func startRecording() {
    let audioFilename = getDocumentsDirectory()

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

    do {
        audioRecorder = try AVAudioRecorder(
              url: audioFilename, settings: settings)
        audioRecorder.delegate = self
    } 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 = 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


One Comment

  1. Ashutosh April 24, 2018 at 5:44 am

    resume recording after incoming call


Leave a Reply

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




Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.