TheCodePig
TheCodePig

Reputation: 122

What is the simplest possible way to add background music to your Swift iOS app?

I have added positional audio and interactive audio to an ARKit, SceneKit game, but now I just want to add background audio that plays when the app is running and open, and stops if the app is closed or in the background. I could use the SceneKit sounds or a mediaplayer, but it seems like there must be a lighter simpler way? Yet, I'm only finding these more complex options, and I don't want to use something that is overkill for any functions in this app. Does anyone know if there is a really simple mechanism for just playing background music?

Upvotes: 0

Views: 383

Answers (1)

Josh Homann
Josh Homann

Reputation: 16327

AVPlayer is pretty simple. Here is my extension to init from URL or filename and loop the audio:

extension AVPlayer {
    convenience init?(url: URL) {
        let playerItem = AVPlayerItem(url: url)
        self.init(playerItem: playerItem)
    }
    convenience init?(name: String, extension ext: String) {
        guard let url = Bundle.main.url(forResource: name, withExtension: ext) else {
            return nil
        }
        self.init(url: url)
    }
    func playFromStart() {
        seek(to: CMTimeMake(0, 1))
        play()
    }
    func playLoop() {
        playFromStart() 
        NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.currentItem, queue: nil) { notification in
            if self.timeControlStatus == .playing {
                self.playFromStart()
            }
        }
    }
    func endLoop() {
        pause()
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self)
    }
}

Upvotes: 1

Related Questions