Aceboy1993 Aceboy1993 - 4 months ago 20
iOS Question

Music not playing when app is in the background Swift Xcode

I've written this code to play music while my app runs but when I go to another app the music stops.

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
playBackgroundMusic("anti.mp3")


}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}

import AVFoundation

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)
}
}


I also added the audio string in the info.plist under required background modes.

I get this output as well, so I thought it would continue playing in the background while using other apps but it does not.

AVAudioSession Category Playback OK
AVAudioSession is Active
AVAudioSession Category Playback OK
AVAudioSession is Active

Answer

Make sure that Audio,Airplay and picture in picture is checked in background modes under capabilities under target under project setup

Check the screenshot

enter image description here

Comments