使用swift 3在后台播放视频的问题

时间:2017-02-09 17:43:33

标签: swift3 avfoundation

我有一个应用程序从互联网上下载视频并通过我的应用程序播放我需要在后台播放视频当用户退出应用程序它仍然工作我怎么能执行此任务我尝试一些问题在网站堆栈溢出但无法解决我的问题,我在下面的代码中添加以下代码来实现它并且也无法正常工作

 override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        UIApplication.shared.beginReceivingRemoteControlEvents()
        self.becomeFirstResponder()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        UIApplication.shared.endReceivingRemoteControlEvents()
        self.resignFirstResponder()
    }

    override func remoteControlReceived(with event: UIEvent?) {
        if event?.subtype == UIEventSubtype.remoteControlPlay {
            print("Play")
        }
    }

我还在Appdelegate中添加以下代码

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let getAvAudioSession = AVAudioSession.sharedInstance()
    do {
          try getAvAudioSession.setActive(true)
          try getAvAudioSession.setCategory(AVAudioSessionCategoryPlayback)
    }catch{
        print(error)
    }
    return true
}

我还在应用程序中启用了功能也不起作用的后台模式

请解决我的问题

非常感谢

1 个答案:

答案 0 :(得分:0)

了解导入MediaPlayer。像下面的东西。

import MediaPlayer

let mpic = MPRemoteCommandCenter.shared()

func setupNowPlayingInfoCenter() {
    UIApplication.shared.beginReceivingRemoteControlEvents()
    mpic.playCommand.addTarget {event in
        print("playCommand")
        self.player?.play()
        return .success
    }
    mpic.pauseCommand.addTarget {event in
        print("pauseCommand")
        if self.player?.rate != 0 {
            self.player?.pause()
        }
        return .success
    }
    mpic.nextTrackCommand.addTarget {event in
        print("nextTrackCommand")
        return .success
    }
    mpic.previousTrackCommand.addTarget {event in
        print("previousTrackCommand")
        return .success
    }

}

不知道你是否真的想在Appdelegate中开始你的音频会话,但这取决于你。当你开始游戏时,基本上调用setupNowPlayingInfoCenter()。