How to continue audio playback in background mode

前端 未结 3 2129
遇见更好的自我
遇见更好的自我 2021-02-14 05:21

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

3条回答
  •  鱼传尺愫
    2021-02-14 05:48

    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.

提交回复
热议问题