AVFoundation is Apple's high-level framework for working with time-based audiovisual media. For audio, it supports:
AVAudioPlayer
AVAudioRecorder
AVAudioEngine
AVCaptureAudioDataOutput
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:
play()
โ Starts playbackpause()
โ Pauses playbackstop()
โ Stops playback and resets position๐๏ธ Useful properties:
volume
โ Adjust playback volume (0.0 to 1.0)numberOfLoops
โ Set to -1
to loop indefinitelyduration
โ Total duration of the audioAVAudioRecorder
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:
AVAudioSession.sharedInstance().setCategory(_:mode:options:)
before recordingAVCaptureDevice.requestAccess(for: .audio)
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:
AVAudioPlayerNode
โ Play audio buffers or filesAVAudioUnitEffect
โ Add effects like reverbAVAudioMixerNode
โ Mix multiple sources๐ง Note: AVAudioEngine is ideal for low-latency audio, real-time FX, and interactive sound design.
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
.
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:
.playback
โ For playing audio only.record
โ For recording only.playAndRecord
โ For both simultaneouslyโ ๏ธ Always activate the session before starting playback or recording!
Here are common issues and how to fix them:
Error Code -10868
โ Incompatible audio format or session misconfiguration. Ensure formats match input/output.nil AVAudioPlayer
โ Ensure the file exists and is not protected or corrupted.