Recording Audio on iOS 9 with AVAudioRecorder

PreviousTable of ContentsNext
Playing Audio on iOS 9 using AVAudioPlayerPreparing and Submitting an iOS 9 Application to the App Store


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


In addition to audio playback, the iOS AV Foundation Framework provides the ability to record sound on iOS using the AVAudioRecorder class. This chapter will work step-by-step through a tutorial demonstrating the use of the AVAudioRecorder class to record audio.

An Overview of the AVAudioRecorder Tutorial

The goal of this chapter is to create an iOS 9 application that will record and playback audio. It will do so by creating an instance of the AVAudioRecorder class and configuring it with a file to contain the audio and a range of settings dictating the quality and format of the audio. Playback of the recorded audio file will be performed using the AVAudioPlayer class which was covered in detail in the chapter entitled Playing Audio on iOS 9 using AVAudioPlayer.

Audio recording and playback will be controlled by buttons in the user interface that are connected to action methods which, in turn, will make appropriate calls to the instance methods of the AVAudioRecorder and AVAudioPlayer objects respectively.

The view controller of the example application will also implement the AVAudioRecorderDelegate and AVAudioPlayerDelegate protocols and a number of corresponding delegate methods in order to receive notification of events relating to playback and recording.

Creating the Recorder Project

Begin by launching Xcode and creating a new Universal single view-based application named Record using the Swift programming language.


Designing the User Interface

Select the Main.storyboard file and, once loaded, drag Button objects from the Object Library window (View -> Utilities -> Show Object Library) and position them on the View window. Once placed in the view, modify the text on each button so that the user interface appears as illustrated in Figure 95-1:


Ios 8 recording demo ui.png

Figure 95-1


With the scene view selected within the storyboard canvas, display the Auto Layout Resolve Auto Layout Issues menu and select the Reset to Suggested Constraints menu option listed in the All Views in View Controller section of the menu.

Select the “Record” button object in the view canvas, display the Assistant Editor panel and verify that the editor is displaying the contents of the ViewController.swift file. Ctrl-click on the Record button object and drag to a position just below the class declaration line in the Assistant Editor. Release the line and, in the resulting connection dialog, establish an outlet connection named recordButton. Repeat these steps to establish outlet connections for the “Play” and “Stop” buttons named playButton and stopButton respectively.

Continuing to use the Assistant Editor, establish Action connections from the three buttons to methods named recordAudio, playAudio and stopAudio.

Close the Assistant Editor panel, select the ViewController.swift file and modify it to import the AVFoundation framework, declare adherence to some delegate protocols and to add properties to store references to AVAudioRecorder and AVAudioPlayer instances:

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate {

    var audioPlayer: AVAudioPlayer?
    var audioRecorder: AVAudioRecorder?
.
.

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Creating the AVAudioRecorder Instance

When the application is first launched, an instance of the AVAudioRecorder class needs to be created. This will be initialized with the URL of a file into which the recorded audio is to be saved. Also passed as an argument to the initialization method is an NSDictionary object indicating the settings for the recording such as bit rate, sample rate and audio quality. A full description of the settings available may be found in the appropriate Apple iOS reference materials.

As is often the case, a good location to initialize the AVAudioRecorder instance is the viewDidLoad method of the view controller located in the ViewController.swift file. Select the file in the project navigator, locate this method and modify it so that it reads as follows:

override func viewDidLoad() {
    super.viewDidLoad()
    playButton.enabled = false
    stopButton.enabled = false

    let fileMgr = NSFileManager.defaultManager()
    let dirPaths = fileMgr.URLsForDirectory(.DocumentationDirectory, inDomains: .UserDomainMask)
    let soundFileURL = dirPaths[0].URLByAppendingPathComponent("sound.caf")

    let recordSettings =
        [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue,
                AVEncoderBitRateKey: 16,
                AVNumberOfChannelsKey: 2,
                AVSampleRateKey: 44100.0]

    let audioSession = AVAudioSession.sharedInstance()

    do {
            try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
    } catch let error as NSError {
        print("audioSession error: \(error.localizedDescription)")
    }

    do {

        try audioRecorder = AVAudioRecorder(URL: soundFileURL,
            settings: recordSettings as! [String : AnyObject])
        audioRecorder?.prepareToRecord()
    } catch let error as NSError {
        print("audioSession error: \(error.localizedDescription)")
    }
}

Since no audio has yet been recorded, the above method disables the play and stop buttons. It then identifies the application’s documents directory and constructs a URL to a file in that location named sound.caf. An NSDictionary object is then created containing the recording quality settings before an audio session and an instance of the AVAudioRecorder class are created. Assuming no errors are encountered, the audioRecorder instance is prepared to begin recording when requested to do so by the user.

Implementing the Action Methods

The next step is to implement the action methods connected to the three button objects. Select the ViewController.swift file and modify it as outlined in the following code excerpt:

@IBAction func recordAudio(sender: AnyObject) {
    if audioRecorder?.recording == false {
        playButton.enabled = false
        stopButton.enabled = true
        audioRecorder?.record()
    }
}

@IBAction func stopAudio(sender: AnyObject) {
    stopButton.enabled = false
    playButton.enabled = true
    recordButton.enabled = true

    if audioRecorder?.recording == true {
        audioRecorder?.stop()
    } else {
        audioPlayer?.stop()
    }
}

@IBAction func playAudio(sender: AnyObject) {
    if audioRecorder?.recording == false {
        stopButton.enabled = true
        recordButton.enabled = false

        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: (audioRecorder?.url)!)
            audioPlayer!.delegate = self
            audioPlayer!.prepareToPlay()
            audioPlayer!.play()
        } catch let error as NSError {
            print("audioPlayer error: \(error.localizedDescription)")
        }
}

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Each of the above methods performs the steps necessary to enable and disable appropriate buttons in the user interface and to interact with the AVAudioRecorder and AVAudioPlayer object instances to record or play back audio.

Implementing the Delegate Methods

In order to receive notification about the success or otherwise of recording or playback it is necessary to implement some delegate methods. For the purposes of this tutorial we will need to implement the methods to indicate errors have occurred and also when playback finished. Once again, edit the ViewController.swift file and add these methods as follows:

func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
    recordButton.enabled = true
    stopButton.enabled = false
}

func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) {
    print("Audio Play Decode Error")
}

func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
}

func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error: NSError?) {
    print("Audio Record Encode Error")
}

Testing the Application

Configure Xcode to install the application on a connect device or simulator session and build and run the application by clicking on the run button in the main toolbar. Once loaded onto the device, the operating system will seek permission to allow the app to access the microphone. Allow access and touch the Record button to record some sound. Touch the Stop button when the recording is completed and use the Play button to play back the audio.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
Playing Audio on iOS 9 using AVAudioPlayerPreparing and Submitting an iOS 9 Application to the App Store