AVAudioRecorder
errors
troubleshooting
iOS development
audio recording

AVAudioRecorder throws errors

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

AVAudioRecorder usually fails for a small set of repeatable reasons: missing microphone permission, a bad audio session, invalid recorder settings, or an unwritable file URL. When you treat setup as a sequence of checks instead of one constructor call, the errors become much easier to diagnose.

Start With Permission and Session Setup

Before creating a recorder, request microphone access and configure the shared audio session. If either step is skipped, the recorder may fail to start or produce vague runtime errors.

swift
1import AVFoundation
2
3func prepareAudioSession() async throws {
4    let session = AVAudioSession.sharedInstance()
5    let granted = await session.requestRecordPermission()
6
7    guard granted else {
8        throw NSError(domain: "RecorderDemo", code: 1, userInfo: [
9            NSLocalizedDescriptionKey: "Microphone permission was denied"
10        ])
11    }
12
13    try session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker])
14    try session.setActive(true)
15}

You also need the microphone usage description in the app’s Info.plist. Without it, iOS can terminate the app when microphone access is requested.

Create the Recorder With Known-Good Settings

Use a writable URL in your app’s sandbox and a format that AVAudioRecorder supports on the device:

swift
1import AVFoundation
2
3final class RecorderController: NSObject, AVAudioRecorderDelegate {
4    private var recorder: AVAudioRecorder?
5
6    func start() throws {
7        let outputURL = FileManager.default.temporaryDirectory
8            .appendingPathComponent("sample.m4a")
9
10        let settings: [String: Any] = [
11            AVFormatIDKey: kAudioFormatMPEG4AAC,
12            AVSampleRateKey: 44100,
13            AVNumberOfChannelsKey: 1,
14            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
15        ]
16
17        recorder = try AVAudioRecorder(url: outputURL, settings: settings)
18        recorder?.delegate = self
19        recorder?.prepareToRecord()
20
21        guard recorder?.record() == true else {
22            throw NSError(domain: "RecorderDemo", code: 2, userInfo: [
23                NSLocalizedDescriptionKey: "Recording did not start"
24            ])
25        }
26    }
27
28    func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
29        print("Encode error:", error?.localizedDescription ?? "unknown error")
30    }
31}

This setup is intentionally plain. It avoids custom sample rates, unusual formats, and custom directories until the basic path works.

Read the Actual Error Instead of Guessing

A common trap is logging only “failed to record.” AVAudioRecorder errors are much more useful when you print the underlying NSError:

swift
1do {
2    try controller.start()
3} catch {
4    let nsError = error as NSError
5    print("Domain:", nsError.domain)
6    print("Code:", nsError.code)
7    print("Description:", nsError.localizedDescription)
8}

That tells you whether the failure is a permission problem, an audio session problem, or a file-system problem.

Validate the Output URL

The recorder writes to a file. If the URL is invalid, points to a protected location, or contains a directory that does not exist, initialization can fail even when audio settings are correct.

This is safe:

swift
let url = FileManager.default.temporaryDirectory
    .appendingPathComponent("recording.m4a")

This is risky if the directory is not guaranteed to exist:

swift
let url = URL(fileURLWithPath: "/recording.m4a")

On iOS, always prefer app-managed directories such as the temporary directory or documents directory.

Simulator Versus Real Device

Audio recording code often behaves differently on the simulator. If the recorder keeps failing and your setup looks correct, move the test to a physical device before changing the implementation. Real hardware exposes microphone permission prompts, route changes, and audio hardware behavior that the simulator cannot fully mimic.

Common Pitfalls

The first common mistake is forgetting the microphone usage description in Info.plist. Permission-related failures often start there.

Another issue is starting the recorder without activating AVAudioSession. The recorder object may be created successfully, but record() can still fail.

Developers also overcomplicate the settings dictionary too early. Start with AAC, a normal sample rate, and one channel. Once recording works, change settings incrementally.

Finally, do not assume a nil error means success. record() returns a Boolean. Check it explicitly and confirm that the file appears on disk after stopping.

Summary

  • Most AVAudioRecorder failures come from permission, session, settings, or file URL problems.
  • Request microphone permission and activate AVAudioSession before creating the recorder.
  • Use a sandboxed writable file path and conservative audio settings first.
  • Log the full NSError so you can see the real failure domain and code.
  • Test on a physical device if simulator behavior is unclear.

Course illustration
Course illustration

All Rights Reserved.