Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue audio playback in background mode

Tags:

ios

audio

I have a UIWebView that plays video clips in my view controller. When I exit the app, the audio will stop playing, although I can press play in the control center to continue it again. To do that I'm using the following code in my AppDelegate.swift.

When the app enters the background, I'd like the audio to start playing automatically. How can I enable the MPMusicPlayerController/AVAudioPlayer (I'm really not sure which it is) to continue playing so the user doesn't have to manually press play?

I also have "Audio and Airplay" checked under Background Modes in my target settings, and Required Background Modes set to "App plays audio or streams audio/video using AirPlay".

var error: NSError?
var success = AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &error)
if !success {
     NSLog("Failed to set audio session category.  Error: \(error)")
}

UPDATE: I'm creating a custom view in my appDel to accommodate a video mini player. Here's how I'm creating it. CustomWindow is a custom class of UIWindow where I'm adding a mini player to the top of the view hierarchy. In this code, am I calling that method before creating the UIWebView?

class AppDelegate: UIResponder, UIApplicationDelegate {

    let myWind = CustomWindow(frame:UIScreen.mainScreen().bounds)
    var window: UIWindow? {
        set {

        }
        get {
            return myWind
        }
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        var error: NSError?
        var success = AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &error)
        if success {
            AVAudioSession.sharedInstance().setActive(true, error: nil)
            UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
        } else {
            NSLog("Failed to set audio session category.  Error: \(error)")
        }

        myWind.showOrHidePopupWindow()
}
like image 528
slider Avatar asked Jul 24 '15 04:07

slider


1 Answers

Try to update you code with this:

var error: NSError?
var success = AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &error)
if success {
    AVAudioSession.sharedInstance().setActive(true, error: nil)
    UIApplication.sharedApplication().beginReceivingRemoteControlEvents() 
} else {
    NSLog("Failed to set audio session category.  Error: \(error)")
}

Important:

  1. Don't use simulator for tests. Background playback doesn't work in the Simulator;
  2. Call above code before creating UIWebView instance.

Sources: 1, 2.

like image 68
Vlad Papko Avatar answered Oct 03 '22 05:10

Vlad Papko