AVFoundation plays audio in background / on lock screen in Swift
I'm trying to find a way with AVFoundation to play audio when the user is on the lock screen, or if they block an 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 do you need to add to this to ensure that sounds are played when the user is also on the lock screen?
+3
source to share
1 answer
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 as sound. Xcode will automatically fill it in as "Require Background Modes" and "Application is playing audio or streaming audio / video using Airplay"
+4
source to share