MVZ
MVZ

Reputation: 2250

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?

Upvotes: 6

Views: 5379

Answers (4)

fatihyildizhan
fatihyildizhan

Reputation: 8832

swift 2+ solution:

audio

do {
  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
  try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
  return print("error")
}

Upvotes: 9

krosh
krosh

Reputation: 218

first of all you should add background mode to your plist like this:enter image description here

Then you should use AVAudioSessionCategoryPlayback session. Like this:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)

AVAudioSessionCategoryAmbient does not work in background.

Upvotes: 1

Alex Antonyuk
Alex Antonyuk

Reputation: 171

You use wrong category, for AVAudioSessionCategoryAmbient it's normal behavior "Your audio is silenced by screen locking and by the Silent switch". Use AVAudioSessionCategoryPlayback instead.

Upvotes: 1

John Difool
John Difool

Reputation: 5702

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>

Upvotes: 1

Related Questions