Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Keep playing sounds when the device is locked

I'm using the following code to play a sound off a URL from the internet:

var audioPlayer = AVPlayer()

...

let audioSession = AVAudioSession.sharedInstance()
audioSession.setCategory(AVAudioSessionCategoryAmbient, error: nil)

let url = trackFileName
let playerItem = AVPlayerItem( URL:NSURL( string:url ) )
audioPlayer = AVPlayer(playerItem:playerItem)
audioPlayer.rate = 1.0;
player.play()

I'm trying to make sure it keeps playing in the background which is the reason why I'm using "AVAudioSession.sharedInstance()". When I try it out in the simulator by locking the screen, it keeps playing like it's supposed to. But if I play it in a device, the sounds shuts off as soon as the screen looks itself automatically or I lock it myself.

What am I missing in my code?

like image 603
MVZ Avatar asked Jun 14 '15 17:06

MVZ


2 Answers

swift 2+ solution:

audio

do {
  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
  try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
  return print("error")
}
like image 81
fatihyildizhan Avatar answered Sep 23 '22 23:09

fatihyildizhan


Open your app info.plist as Source code (to edit in text mode) and add the following just after dict:

<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
</array>
like image 20
John Difool Avatar answered Sep 22 '22 23:09

John Difool