【问题标题】:issue with play video in background using swift 3使用 swift 3 在后台播放视频的问题
【发布时间】:2017-02-09 17:43:33
【问题描述】:

我有一个应用程序,从互联网下载视频并通过我的应用程序播放我需要在用户退出应用程序时在后台播放视频它仍然工作我如何执行此任务我尝试一些关于站点堆栈溢出的问题但无法解决我的问题,我添加了以下代码来制作它并且也无法正常工作

 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
}

而且我还在应用程序中启用后台模式,但功能也不起作用

请帮我修一下

非常感谢

【问题讨论】:

    标签: swift3 avfoundation


    【解决方案1】:

    考虑导入 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()。

    【讨论】:

    • 这是不正确的:setupNowPlayingInfoCenter()应该被启动到viewDidLoad方法,你不应该每次开始播放或者关闭MPRemoteCommandCenter时调用它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 2015-03-02
    相关资源
    最近更新 更多