How do I record audio and manage permissions in Swift?

Recording audio and managing permissions in Swift can be accomplished through the AVFoundation framework. Below is an example of how to request microphone permissions, handle the audio recording, and manage the audio session.

import UIKit import AVFoundation class ViewController: UIViewController, AVAudioRecorderDelegate { var audioRecorder: AVAudioRecorder! override func viewDidLoad() { super.viewDidLoad() requestMicrophonePermission() } func requestMicrophonePermission() { AVAudioSession.sharedInstance().requestRecordPermission { granted in if granted { self.setupAudioRecorder() } else { print("Permission to record not granted") } } } func setupAudioRecorder() { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(.playAndRecord, mode: .default) try audioSession.setActive(true) let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let audioURL = documentsDirectory.appendingPathComponent("recording.m4a") let settings: [String: Any] = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 44100, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] audioRecorder = try AVAudioRecorder(url: audioURL, settings: settings) audioRecorder.delegate = self audioRecorder.prepareToRecord() audioRecorder.record() } catch { print("Failed to setup audio recorder: \(error)") } } func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { if flag { print("Recording finished successfully") } else { print("Recording failed") } } }

Swift Audio Recording AVFoundation Microphone Permission Audio Session