视频播放结束后如何返回 tvOS 中的 Main.storyboard?
Posted
技术标签:
【中文标题】视频播放结束后如何返回 tvOS 中的 Main.storyboard?【英文标题】:How to return back to Main.storyboard in tvOS after playback of video ends? 【发布时间】:2015-12-31 09:43:25 【问题描述】:我有一个播放器,并且已被指示如何为itemDidFinishPlaying
设置通知:(AVPlayerItemDidPlayToEndTimeNotification
),但是,由于某种原因,该通知函数不会在结束时调用视频。
import UIKit
import AVKit
class ViewController: UIViewController
let playerLayer = AVPlayerLayer()
func playMe(inputfile: String, inputtype: String)
let path = NSBundle.mainBundle().pathForResource(inputfile, ofType:inputtype)!
let videoURL = NSURL(fileURLWithPath: path)
let playerItem = AVPlayerItem(URL: videoURL)
let player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
print ("Play has started")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "itemDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
print ("Item Did Finish Playing -notification added")
func itemDidFinishPlaying(notification: NSNotification)
playerLayer.removeFromSuperlayer()
print ("Notification sent with removeFromSuperlayer done")
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
我错过了什么?我试过在viewDidLoad()
有通知条目,我试过从itemDidFinishPlaying
的末尾删除:,我试过在播放开始之前设置通知,我在NSNotificationCenter
中有object: nil
和object:playerItem
..
我真的很不知道如何进行。
这些类型的东西是否仅在具有 AVPlayerViewController
或按下按钮时生成的辅助视图控制器时可用?
【问题讨论】:
【参考方案1】:如果您没有对 AVPlayer
实例的引用,这似乎会发生。试试这个:
import UIKit
import AVFoundation
class ViewController: UIViewController
var player: AVPlayer?
var playerLayer: AVPlayerLayer?
func playMe(inputfile: String, inputtype: String)
guard let path = NSBundle.mainBundle().pathForResource(inputfile, ofType: inputtype) else
print("couldn't find \(inputfile).\(inputtype)")
return
player = AVPlayer()
playerLayer = AVPlayerLayer(player: player)
let playerItem = AVPlayerItem(URL: NSURL(fileURLWithPath: path))
player?.replaceCurrentItemWithPlayerItem(playerItem)
playerLayer.frame = view.bounds
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.itemDidFinishPlaying(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: player?.currentItem)
view.layer.insertSublayer(playerLayer!, atIndex: 0)
player?.play()
func itemDidFinishPlaying(notification: NSNotification)
playerLayer?.removeFromSuperlayer()
print ("Notification sent with removeFromSuperlayer done")
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
这应该可以解决问题。
别忘了移除观察者
deinit
NSNotificationCenter.defaultCenter().removeObserver(self)
【讨论】:
以上是关于视频播放结束后如何返回 tvOS 中的 Main.storyboard?的主要内容,如果未能解决你的问题,请参考以下文章