结合使用Swift和AVPlayer,如何通过代码添加和删除视频? [英] Using Swift with AVPlayer, how do you add and remove a video via code?

查看:118
本文介绍了结合使用Swift和AVPlayer,如何通过代码添加和删除视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的新手,正在尝试将视频添加到视图中,然后在派发"stopScreenSaver"通知时将其删除.除了我要删除视频层(playerLayer.removeFromSuperlayer())以外,其他所有方法似乎都正常运行.

I'm new to Swift and am trying to add a video to the view and then remove it when my "stopScreenSaver" notification is dispatched. All seems to work well except for when I go to remove the video layer (playerLayer.removeFromSuperlayer()).

任何指导将不胜感激.我觉得我在这里缺少添加和删除图层的一些基本概念!

Any guidance would be appreciated. I feel like I'm missing some basic concept here for adding and removing the layer!

    import UIKit
    import AVFoundation
    import QuartzCore
    import CoreMedia

    class ViewController: UIViewController {

        let contentURL = NSBundle.mainBundle().URLForResource("testvideo", withExtension: "mp4")
        var player = AVPlayer()
        var playerLayer = AVPlayerLayer()
        let screenSize : CGRect = UIScreen.mainScreen().bounds

        override func viewDidLoad() {
            super.viewDidLoad()
            // Used for starting and stopping the videos related to the screen saver
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "playScreenSaver:", name: "playScreenSaverID", object: nil)
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "stopScreenSaver:", name: "stopScreenSaverID", object: nil)
}

        override func viewDidAppear(animated: Bool) {
            // Player
            player = AVPlayer(URL: contentURL!)

            // Layer for display… Video plays at the full size of the iPad
            playerLayer = AVPlayerLayer(player: player)
            var view = UIView(frame: CGRectMake(0, 0, screenSize.width, screenSize.height))
            self.view.layer.addSublayer(playerLayer)
            playerLayer.frame = view.bounds
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }


    func playScreenSaver(notification: NSNotification){
            print("play")
            dispatch_async(dispatch_get_main_queue()) {
               self.view.layer.addSublayer(self.playerLayer!)
               self.player!.play()
            }
    }

    func stopScreenSaver(notification: NSNotification){
            print("pause")
            dispatch_async(dispatch_get_main_queue()) {
               self.player!.pause()
               self.playerLayer!.removeFromSuperlayer()
            }
    }

}

推荐答案

使用分发程序解决了我遇到的问题.

Using the dispatch fixed the issue I was having.

dispatch_async(dispatch_get_main_queue()) {
    self.player!.pause()
    self.playerLayer!.removeFromSuperlayer()
 }

这篇关于结合使用Swift和AVPlayer,如何通过代码添加和删除视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆