skip to content

With AVFAudio, how do you record a spoken count-in as a voice note with AVAudioRecorder, starting from the microphone permission request?

level: middleimportance: should knowfreq 50%

answer

  1. permission, session, recorder, in that order
  2. the iOS 17 home of record permission
  3. a category that records and plays
  4. a file URL plus a settings dictionary
  5. earpiece output unless one option is set

basics

~10 s

Request permission with AVAudioApplication.requestRecordPermission() (iOS 17), set the audio session to .playAndRecord and activate it, then create AVAudioRecorder with a file URL and a settings dictionary and call record(); stop() finishes the file.

solid answer

~30 s

The Info.plist needs `NSMicrophoneUsageDescription`. On iOS 17 and later I ask with `AVAudioApplication.requestRecordPermission()` (or its completion-handler form), which replaced AVAudioSession's `requestRecordPermission(_:)`, deprecated in iOS 17. Then the session: `setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker])` and `setActive(true)`, because recording requires `.record` or `.playAndRecord`, and I want to play the take back. Then `AVAudioRecorder(url:settings:)` with keys such as `AVFormatIDKey: kAudioFormatMPEG4AAC`, `AVSampleRateKey` and `AVNumberOfChannelsKey`, kept in a property, and `record()`, which calls `prepareToRecord()` itself. `stop()` closes the file, and `AVAudioPlayer(contentsOf:)` plays it back. Anything with live processing goes to AVAudioEngine instead.

code

swift · 26 lines
swift
import AVFAudio

@MainActor
final class CountInRecorder {
    private var recorder: AVAudioRecorder? // keep it alive while recording

    func start(to fileURL: URL) async throws -> Bool {
        guard await AVAudioApplication.requestRecordPermission() else { return false }
        let session = AVAudioSession.sharedInstance()
        try session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker])
        try session.setActive(true)
        let settings: [String: Any] = [
            AVFormatIDKey: kAudioFormatMPEG4AAC,
            AVSampleRateKey: 44_100.0,
            AVNumberOfChannelsKey: 1,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ]
        let recorder = try AVAudioRecorder(url: fileURL, settings: settings)
        self.recorder = recorder
        return recorder.record() // prepareToRecord() runs automatically
    }

    func stop() {
        recorder?.stop() // finishes writing the file
    }
}

go deeper

for a junior

Recall the three steps, permission, session category, recorder, and that the microphone needs its own usage string.

for a middle

Explain the iOS 17 move to AVAudioApplication, why playAndRecord with defaultToSpeaker, and what each settings key controls.

for a senior

Show you can trace a quiet playback, a missing file or a stuck permission flow to its cause, and keep an iOS 16 fallback tidy.

for a principal

Decide where AVAudioRecorder stops being enough and live processing justifies an audio engine, given the cost of owning it.

## What the feature needs A voice note, the instructor saying "five, six, seven, eight" before a routine, is the simplest recording job in AVFAudio, and it touches three things in order: 1. **Permission** to use the microphone. 2. An **audio session** configured for recording. 3. An **`AVAudioRecorder`** that writes a file. `AVAudioRecorder` records from the system's active input device to a file, for a set duration or until stopped, and can pause, resume and meter levels. Signal processing on live audio is outside it; Apple points to AVAudioEngine for that, and the Core Audio lesson covers it. ## Microphone permission and the iOS 17 move The Info.plist must contain **`NSMicrophoneUsageDescription`**, the text the system shows in the alert. The permission API moved in **iOS 17**: | API | Status in the iOS 27.1 SDK | |---|---| | `AVAudioApplication.requestRecordPermission(completionHandler:)` and its `async` form | available from iOS 17 | | `AVAudioApplication.shared.recordPermission` | available from iOS 17, values `.undetermined`, `.denied`, `.granted` | | `AVAudioSession`'s `requestRecordPermission(_:)` | deprecated in iOS 17, "Please use AVAudioApplication" | | `AVAudioSession`'s `recordPermission` | deprecated in iOS 17 | The header notes that the response block is called immediately if the user already answered, otherwise after the alert is dismissed, and that it **may be called on a different thread**. The `async` form used from a `@MainActor` type sidesteps that: the code after `await` resumes on the main actor. An app that still supports iOS 16 keeps the old call behind `if #available`. ## Configuring the session for recording Apple's `AVAudioRecorder` page is explicit: to record on iOS, configure the session with the **`.record`** or **`.playAndRecord`** category. For a count-in the user will want to hear back, `.playAndRecord` is the fit, because `.record` is the category for recording alone. One option matters here. With `.playAndRecord`, output goes to the **receiver**, the earpiece at the top of the iPhone, unless you pass **`.defaultToSpeaker`**, which routes to the speaker when no other route is connected. The header adds that in every other category `defaultToSpeaker` is always false and cannot be changed. Forgetting it produces the classic bug report: "the voice note plays back so quietly". Then `setActive(true)` activates the session. It is a synchronous call that can take time; iOS 27 adds an asynchronous `activate()` for code that cannot block. ## Creating and running the recorder `AVAudioRecorder(url:settings:)` throws, and takes a file URL in a writable location (the app's Documents or a temporary directory) plus a **settings dictionary**: - `AVFormatIDKey`: the codec, for example `kAudioFormatMPEG4AAC` for a compact `.m4a` file, or `kAudioFormatLinearPCM` for uncompressed audio. - `AVSampleRateKey`: such as `44_100.0`. - `AVNumberOfChannelsKey`: `1` is plenty for speech. - `AVEncoderAudioQualityKey`: an `AVAudioQuality` raw value. The controls are plain: `prepareToRecord()` creates the output file and gets ready to record, and `record()` calls it automatically if you have not; `record()` and `prepareToRecord()` return `Bool` for success; `pause()` and `record()` resume; `record(forDuration:)` stops by itself; `stop()` finishes the file; `deleteRecording()` removes it once the recorder is stopped. `isRecording` and the delegate's `audioRecorderDidFinishRecording(_:successfully:)` report state. Keep the recorder in a property: a local constant is released when the function returns. A count-in screen often shows a level meter so the instructor can see the microphone is live. Set `isMeteringEnabled = true`, call `updateMeters()` on a timer or display tick, and read `averagePower(forChannel:)` or `peakPower(forChannel:)`, both in decibels. `currentTime` gives the elapsed recording time for a running clock beside it. ## Playing the count-in back `AVAudioPlayer(contentsOf:)` plays the finished file: `prepareToPlay()`, `play()`, `numberOfLoops` for repetition and `volume` for level. Its delegate's `audioPlayerDidFinishPlaying(_:successfully:)` is documented as **not called when an interruption stops the player**, so a phone call needs the audio session's interruption handling instead. ## Mistakes worth catching in review - Calling the deprecated `AVAudioSession` permission API in new iOS 17+ code. - Recording in `.playback` or `.ambient`, when Apple's page names `.record` or `.playAndRecord`. - Playing back in `.playAndRecord` without `.defaultToSpeaker`. - Reading or uploading the file before `stop()`. - Updating UI straight from a completion handler that may run off the main thread. - Holding the recorder in a local constant, so it is released as soon as the method returns.

  • The app still supports iOS 16; how do you request permission there?
    Behind `if #available(iOS 17, *)` call `AVAudioApplication.requestRecordPermission`; in the `else` branch call AVAudioSession's `requestRecordPermission(_:)`, which is deprecated from iOS 17 but is the only API on iOS 16. Remove the branch once the deployment target reaches iOS 17.
  • Why does the count-in play from the earpiece, and how do you fix it?
    In `.playAndRecord`, output defaults to the receiver. Passing `.defaultToSpeaker` in the category options routes it to the speaker when no headphones or other route is connected; the option is valid only with `.playAndRecord`.
  • When would you leave AVAudioRecorder for something else?
    When the audio must be processed while it is captured, such as a live metronome mix or level-driven effects. Apple points to AVAudioEngine for that, which belongs with the Core Audio material; a plain voice note stays with `AVAudioRecorder`.

  • AVAudioSession's requestRecordPermission(_:) is the current API on iOS 17
  • The .playback category is enough for AVAudioRecorder to record
  • record() fails unless prepareToRecord() was called first
  • playAndRecord sends output to the speaker by default
  • The permission callback always arrives on the main thread

Assumes the iOS 27.1 SDK; AVAudioApplication's record permission arrived in iOS 17, when AVAudioSession's requestRecordPermission(_:) was deprecated.