๐ŸŽง Overview of AVFoundation Audio

AVFoundation is Apple's high-level framework for working with time-based audiovisual media. For audio, it supports:

๐Ÿ“ผ AVAudioPlayer โ€“ Playback

AVAudioPlayer is used to play audio files locally from the app bundle or filesystem.


let url = URL(fileURLWithPath: "/path/to/audio.mp3")
let player = try AVAudioPlayer(contentsOf: url)
player.prepareToPlay()
player.play()
    

๐Ÿ” Common methods:

๐ŸŽ›๏ธ Useful properties:

๐ŸŽ™๏ธ AVAudioRecorder โ€“ Recording

AVAudioRecorder allows you to capture microphone input and save it to a file.


let settings = [
    AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
    AVSampleRateKey: 12000,
    AVNumberOfChannelsKey: 1,
    AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
let recorder = try AVAudioRecorder(url: fileURL, settings: settings)
recorder.record()
    

๐Ÿ“Œ Tips:

๐ŸŽ›๏ธ AVAudioEngine โ€“ Advanced Audio Graph

AVAudioEngine provides a powerful modular system for manipulating audio streams in real time.


let engine = AVAudioEngine()
let playerNode = AVAudioPlayerNode()
engine.attach(playerNode)

let mixer = engine.mainMixerNode
engine.connect(playerNode, to: mixer, format: nil)

try engine.start()
playerNode.play()
    

โš™๏ธ Core Components:

๐Ÿง  Note: AVAudioEngine is ideal for low-latency audio, real-time FX, and interactive sound design.

๐Ÿ“ก Capturing Live Audio โ€“ AVCaptureAudioDataOutput

This is part of AVCaptureSession and allows you to get live microphone data in real-time buffers.


let audioOutput = AVCaptureAudioDataOutput()
audioOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "audioQueue"))
captureSession.addOutput(audioOutput)
    

๐Ÿงช You can use this to pipe audio into an AVAudioEngine or encode it manually using AudioToolbox.

๐Ÿงฉ Audio Session Management

Before playing or recording, configure your AVAudioSession to inform the system how your app uses audio.


let session = AVAudioSession.sharedInstance()
try session.setCategory(.playAndRecord, mode: .default)
try session.setActive(true)
    

๐Ÿ“Œ Categories:

โš ๏ธ Always activate the session before starting playback or recording!

๐Ÿ› ๏ธ Troubleshooting & Common Errors

Here are common issues and how to fix them: