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")
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?