Skip to content

Instantly share code, notes, and snippets.

@standinga
Created May 4, 2019 00:31
Show Gist options
  • Save standinga/7b08ca2cd7ddf2feaaa68a04d11523a8 to your computer and use it in GitHub Desktop.
Save standinga/7b08ca2cd7ddf2feaaa68a04d11523a8 to your computer and use it in GitHub Desktop.
updated AudioPlayer.swift for medium post about Audio Unit V3 Extensions
public func selectAudioUnitWithComponentDescription(_ componentDescription: AudioComponentDescription?, completionHandler: @escaping (() -> Void)) {
// Internal function to resume playing and call the completion handler.
func done() {
if isPlaying {
playerNode.play()
}
completionHandler()
}
let hardwareFormat = self.engine.outputNode.outputFormat(forBus: 0)
self.engine.connect(self.engine.mainMixerNode, to: self.engine.outputNode, format: hardwareFormat)
/*
Pause the player before re-wiring it. (It is not simple to keep it
playing across an insertion or deletion.)
*/
if isPlaying {
playerNode.pause()
}
// Destroy any pre-existing unit.
if audioUnitNode != nil {
// Break player -> effect connection.
engine.disconnectNodeInput(audioUnitNode!)
// Break audioUnitNode -> mixer connection
engine.disconnectNodeInput(engine.mainMixerNode)
// Connect player -> mixer.
engine.connect(playerNode, to: engine.mainMixerNode, format: file!.processingFormat)
// We're done with the unit; release all references.
engine.detach(audioUnitNode!)
audioUnitNode = nil
audioUnit = nil
}
// Insert the audio unit, if any.
if let componentDescription = componentDescription {
AVAudioUnit.instantiate(with: componentDescription, options: []) { avAudioUnit, error in
guard let avAudioUnit = avAudioUnit else {
NSLog("avAudioUnit nil")
return
}
self.audioUnitNode = avAudioUnit
self.engine.attach(avAudioUnit)
// Disconnect player -> mixer.
self.engine.disconnectNodeInput(self.engine.mainMixerNode)
// Connect player -> effect -> mixer.
self.engine.connect(self.playerNode, to: avAudioUnit, format: self.file!.processingFormat)
self.engine.connect(avAudioUnit, to: self.engine.mainMixerNode, format: self.file!.processingFormat)
self.audioUnit = avAudioUnit.auAudioUnit
avAudioUnit.auAudioUnit.contextName = "running in AUv3Host"
done()
}
} else {
done()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment