gregm
gregm

Reputation: 12159

How to I make my IOS app play music in the background forever?

I want to write a music player iOS app that plays music in a loop in the background. I do not want the music to stop. Also, I want to run a timer that executes updates every once in a while that might change the music played.

I have setup my app for "audio" background exectution and I have code like this to start playing audio:

try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with:AVAudioSessionCategoryOptions.mixWithOthers)  
try AVAudioSession.sharedInstance().setActive(true)  
let player = try AVAudioPlayer(contentsOf: sound)  
player.numberOfLoops = -1  
player.prepareToPlay()  
player.delegate = self  
player.play()  

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {  
  player.play()  
}  

Why does iOS kill my app and make it stop playing music and running my Timer?

Upvotes: 3

Views: 1615

Answers (1)

Dharay
Dharay

Reputation: 305

Use MPMusicPlayerController.systemMusicPlayer instead of AVAudioPlayer https://developer.apple.com/documentation/mediaplayer/mpmusicplayercontroller?language=objc

Upvotes: 2

Related Questions