I have this simple Swift code that uses an AVAudioEngine + AVAudioPlayerNode to play an audio file on loop.
When I start the app the audio plays on the laptop speakers. If I switch my computer's output to a HomePod mini, the audio on the laptop stops but never plays on the HomePod mini (the mini also doesn't light up).
If I stop the app and run it again - the audio plays on the HomePod mini. If I switch back to the laptop - the audio stops until I restart the app, etc.
It seems the problem is with switching the output device during playback, but I cannot understand how to fix this. Below is my code:
class AppDelegate: NSObject, NSApplicationDelegate {
var engine = AVAudioEngine()
var player = AVAudioPlayerNode()
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Attach audio player
engine.attach(player)
// Load audio file
let filePath = Bundle.main.path(forResource: "sheep1.m4a", ofType: nil)!
let fileURL = URL(fileURLWithPath: filePath)
let file = try! AVAudioFile(forReading: fileURL)
// Load the audio buffer
let fileFormat = file.processingFormat
let fileFrameCount = UInt32(file.length)
let buffer = AVAudioPCMBuffer(pcmFormat: fileFormat, frameCapacity: fileFrameCount)
try! file.read(into: buffer!, frameCount: fileFrameCount)
// Connect to the mixer
let mainMixer = engine.mainMixerNode
engine.connect(player, to: mainMixer, format: file.processingFormat)
// Start the engine
try! engine.start()
// Play the audio
player.scheduleBuffer(buffer!, at: nil, options: .loops, completionHandler: nil)
player.play()
}
}