gpt4 book ai didi

ios - 将 Swift 与 AVPlayer 一起使用,如何通过代码添加和删除视频?

转载 作者:搜寻专家 更新时间:2023-10-31 22:34:39 27 4
gpt4 key购买 nike

我是 Swift 的新手,正在尝试将视频添加到 View ,然后在发送“stopScreenSaver”通知时将其删除。除了我去删除视频层 (playerLayer.removeFromSuperlayer()) 之外,一切似乎都运行良好。

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

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

}

最佳答案

使用 dispatch 解决了我遇到的问题。

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

关于ios - 将 Swift 与 AVPlayer 一起使用,如何通过代码添加和删除视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32726269/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com