CodexBloom - Programming Q&A Platform

implementing AVAudioPlayer not playing audio after switching to a different NSViewController on macOS 13.6

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
macos AVFoundation AVAudioPlayer Swift

I'm trying to implement Could someone explain I've looked through the documentation and I'm still confused about I'm working with a question with AVAudioPlayer in my macOS app. I have an audio file that needs to play in the background when I switch between different NSViewControllers. However, after I switch to a different NSViewController, the audio stops playing. It seems like the player is being deallocated or not properly retained. I've tried explicitly retaining the AVAudioPlayer instance and ensuring it's a property of my main view controller, but I'm still having issues. Here's the code snippet where I'm initializing and playing the audio: ```swift import AVFoundation class MainViewController: NSViewController { var audioPlayer: AVAudioPlayer? func playAudio() { guard let url = Bundle.main.url(forResource: "audioFile", withExtension: "mp3") else { return } do { audioPlayer = try AVAudioPlayer(contentsOf: url) audioPlayer?.play() } catch { print("behavior initializing player: \(behavior)") } } override func viewDidAppear() { super.viewDidAppear() playAudio() } } ``` Additionally, I'm using the following method to switch view controllers: ```swift func switchToNextView() { let nextViewController = NextViewController() self.presentAsModalWindow(nextViewController) } ``` I want the audio to continue playing seamlessly during the transition. I also checked for any relevant notifications from AVAudioSession, but they don't seem to provide any insights. Is there a specific configuration I might be missing, or should I be handling the audio player differently to ensure it continues during view controller transitions? Any help would be greatly appreciated! This is part of a larger application I'm building. I'm on macOS using the latest version of Swift.