Search code examples
swiftmacosdelegatesavaudioplayer

Control background music in Swift (macOS)


I am developing a macOS app that basically plays some sound in the background. The only issue that I have is that the audio plays from the App Delegate to keep it going when the app runs in background, however I do not know how to stop or play the audio from my View Controller. In AppDelegate.swift:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {


var audioURL = URL(fileURLWithPath: Bundle.main.path(forResource: "audio", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()

let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)



func applicationDidFinishLaunching(_ aNotification: Notification) {




    do {
        audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
        audioPlayer.prepareToPlay()
        audioPlayer.volume = 0.2
    } catch {
        print("Sorry, couldn't load the audio file")
    }
}

I was thinking about using a delegate, but I am new both to UIs as well as C#/Swift, so I really don't know how to implement one.


Solution

  • Your view controller can get a reference to the app delegate with

    if let appDelegate = NSApp.delegate as? AppDelegate {
        // do something with appDelegate.audioPlayer
        // ...
    }