4

I'm trying to find a way with AVFoundation to play audio when the user is on the lock screen or if they lock the app in the middle of using my app

class ViewController: UIViewController, AVAudioPlayerDelegate {
    var avPlayer: AVAudioPlayer?
    var error: NSError?

... other stuff ... 

    func playChime(fileName: String) -> Void {
        let fileURL: NSURL! = NSBundle.mainBundle().URLForResource(fileName, withExtension: "wav")
        self.avPlayer = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
        self.avPlayer?.play()
    }
... other stuff ... 
}

What needs to be added to this to ensure sounds play when the user is on the lock screen as well?

Zack Shapiro
  • 6,648
  • 17
  • 83
  • 151
  • 1
    Similar case but in Objective-C: http://stackoverflow.com/questions/7619794/play-music-in-the-background-using-avaudioplayer – Raptor Jan 06 '15 at 06:36

1 Answers1

5

To continue playing audio in the background when the device is locked or on the home screen (on Xcode 6.3):

Add to your ViewController:

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

Then in your Info.plist, add a new entry for UIBackgroundModes and set it to audio. Xcode will automatically fill it out as 'Require background modes' and 'App plays audio or streams audio/video using Airplay'

David T
  • 2,724
  • 1
  • 17
  • 27