How to continue audio playback in background mode

前端 未结 3 2116
遇见更好的自我
遇见更好的自我 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:40

    You can play music in lockscreen with

    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)")
    }
    

    After it You Need to add Background Modes in the capabilities Like this. And don't test this on simulator It does not work on simulator. Hope it helps

    and this is how you can handal previous,next,pause and play :-

    - (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent
    
     {
    
        if (receivedEvent.type == UIEventTypeRemoteControl) 
    {
            switch (receivedEvent.subtype)
     {
                case UIEventSubtypeRemoteControlTogglePlayPause:
                    [self togglePlayPause];
                    break;
                case UIEventSubtypeRemoteControlPreviousTrack:
                    [self playPrevTrack];
                    break;
                case UIEventSubtypeRemoteControlNextTrack:
                    [self playNextTrack];
                    break;
                default:
                    break;
            }
        }
    }
    

    In swift you can use it Like that

    override func remoteControlReceivedWithEvent(event: UIEvent) {
            let rc = event.subtype
    
            println("received remote control \(rc.rawValue)") // 101 = pause, 100 = play
            switch rc {
            case .RemoteControlTogglePlayPause:
    
                self.togglePlayPause()
            break;
            case .RemoteControlPreviousTrack:
                self.playPrevTrack()
             break;
            case .RemoteControlNextTrack:
                self.playNextTrack()
            break;
            default:break
            }
    

提交回复
热议问题