Skip to content

Instantly share code, notes, and snippets.

@lijon
Created August 11, 2023 11:23
Show Gist options
  • Save lijon/95135e7a98d065650c3854fdf4fd51a3 to your computer and use it in GitHub Desktop.
Save lijon/95135e7a98d065650c3854fdf4fd51a3 to your computer and use it in GitHub Desktop.
Audio Session init

setup AVAudioSession

Add NSNotificationCenter observers for AVAudioSessionRouteChangeNotification, AVAudioSessionInterruptionNotification and AVAudioSessionMediaServicesWereResetNotification

requestRecordPermission

setCategory: AVAudioSessionCategoryPlayAndRecord withOptions: AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionAllowBluetoothA2DP | AVAudioSessionCategoryOptionAllowAirPlay | AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption // iOS 14.5 and later only

setAggregatedIOPreference:AVAudioSessionIOTypeAggregated

setPreferredSampleRate

setPreferredIOBufferDuration:(double)preferredBufferSize/audioSession.sampleRate

setPrefersNoInterruptionsFromSystemAlerts:YES // iOS 14.5 and later only

setActive:YES

setup main I/O audio unit

Create kAudioUnitSubType_RemoteIO AudioUnit

register property listeners for kAudioOutputUnitProperty_IsRunning, kAudioUnitProperty_StreamFormat

kAudioOutputUnitProperty_EnableIO = 1 on output scope element 0 and input scope element 1

set kAudioUnitProperty_MaximumFramesPerSlice on global scope element 0

install MainRenderCallback with kAudioUnitProperty_SetRenderCallback on input scope element 0

AudioUnitInitialize

StreamFormatCallback

get kAudioUnitProperty_StreamFormat

checks if it's the input (input scope, element 1) or output (output scope, element 0) and update the client-side format to match the sample rate and number of channels by setting kAudioUnitProperty_StreamFormat for input (output scope element 1) or output (input scope element 0).

check if sample rate changed and scope was output, if yes then dispatch on main queue:

  • AudioOutputUnitStop(mainAudioUnit)
  • Update all internals that depend on sample rate
  • Set bus format with new rate on all hosted AUv3 plugins
  • AudioOutputUnitStart(mainAudioUnit) // if it was running

AVAudioSession route change callback

dispatch on main queue:

audioSession setPreferredInputNumberOfChannels: audioSession.maximumInputNumberOfChannels

audioSession setPreferredOutputNumberOfChannels: audioSession.maximumOutputNumberOfChannels

enumerate audioSession.currentRoute.inputs and outputs to get a list of audio ins and outs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment