4
votes

First of all, I'm not asking how to play AVPlayer in the background. There are plenty of solution for that. My problem is a bit different.

AVPlayer in my application is playing an array of "AVPlayerItem". And when the last song is finished I start the player from the first songs. This works completely fine when the application is in the active state but, if while playing the song I press the home button and the last song is finished playing in the background. Now the player stops here, it doesn't start the first song again.

Any idea why this kind of behaviour and what could be the solution.

1

1 Answers

3
votes

You need to set this: enter image description here

Then, Follow as:

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    print("AVAudioSession Category Playback OK")
    do {
        try AVAudioSession.sharedInstance().setActive(true)
         UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
        print("AVAudioSession is Active")
    } catch let error as NSError {
        print(error.localizedDescription)
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

Also, To play Audio:

var backgroundMusicPlayer = AVAudioPlayer()

func playBackgroundMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
    guard let newURL = url else {
        print("Could not find file: \(filename)")
        return
    }
    do {
        backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
        backgroundMusicPlayer.numberOfLoops = -1
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()
    } catch let error as NSError {
        print(error.description)
    }
}

Then, Mainly:

override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        self.becomeFirstResponder()
        UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
    }

And in Final in your AppDelegate you'll receive event at:

override func remoteControlReceivedWithEvent(event: UIEvent?) {
        let rc = event!.subtype
        print("does this work? \(rc.rawValue)")
    }