---
title: "#107: Audio Recording Basics 🎤"
url: https://littlebitesofcocoa.com/107-audio-recording-basics
author: Jake Marsh
date: 2015-10-20
published: 2015-10-20
topics: ["AVFoundation","Media","Audio"]
description: "Today we'll take a look at how to record audio from the microphone on a user's device. Let's get started. The first thing we'll need is an Audio Session."
---

# #107: Audio Recording Basics 🎤

By Jake Marsh, October 20, 2015. HTML: https://littlebitesofcocoa.com/107-audio-recording-basics

Today we'll take a look at how to _record audio_ from the microphone on a user's **device**. Let's get started.

The first thing we'll need is an **Audio Session**. This will be a **singleton** ([Bite #4](https://littlebitesofcocoa.com/4)), and we'll also create a property to hold our `recorder`:

``` swift
import AVFoundation

class RecordViewController : UIViewController {
  let session = AVAudioSession.sharedInstance()
  var recorder: AVAudioRecorder?
}
```

Next, we'll create a **function** to start recording:

``` swift
func beginRecording() {
  session.requestRecordPermission { granted in
    guard granted else { return }

    do {
      try self.session.setCategory(AVAudioSessionCategoryPlayAndRecord)
      try self.session.setActive(true)

      let recordingFileName = "recording.caf"

      guard let recordingURL = documentsDirectoryURL()?
        .URLByAppendingPathComponent(recordingFileName) else { return }

      let settings: [String : AnyObject] = [
        AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue,
        AVSampleRateKey: 12000.0,
        AVNumberOfChannelsKey: 1,
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC)
      ]

      try self.recorder = AVAudioRecorder(
        URL: recordingURL, 
        settings: settings
      )
    } catch { }
  }
}

```

We'll first need to request permission from the user to record audio. Once granted, we'll try to set our **Audio Session's** category to <i>PlayAndRecord</i>, the category Apple suggests for apps that simultaneously record and playback audio.

We'll create a place for our recording to live, then assemble the settings dictionary for our recorder. We instantiate and store our **AVAudioRecorder** object, then tell it to start recording. Later, we'll call `.stop()` on it to stop recording. We can also optionally wire up a **delegate** to get completion callbacks.

Finally, we can play back our file using **AVAudioPlayer**: 

``` swift
let audioPlayer = try AVAudioPlayer(contentsOfURL: recordingURL)
audioPlayer.prepareToPlay()
audioPlayer.play()
```
