我在使用AVPlayer在快速游乐场内播放视频时遇到问题。
这是我的代码。
import UIKit
import AVFoundation
var f=CGRectMake(0, 0, 500, 500)
var url=NSURL(string: "http://s3.amazonaws.com/vids4project/sample.mp4")
var playerItem = AVPlayerItem(URL: url)
var v = UIView(frame:f)
var player=AVPlayer(playerItem: playerItem)
var playerLayer=AVPlayerLayer(player: player)
playerLayer.frame=f
v.layer.addSublayer(playerLayer)
player.play()
有什么建议吗?代码完全没有任何作用。我的期望是' v'变量应该显示视频。当我将avplayerlayer连接到故事板的视图时,它似乎在操场外工作。
答案 0 :(得分:7)
如果将它放入游乐场,以下情况应该有效。确保换出路径:(Xcode7 GM)
import UIKit
import AVFoundation
import XCPlayground
var f = CGRectMake(0, 0, 500, 500)
let path = NSBundle.mainBundle().pathForResource("movie", ofType: "m4v")!
let url = NSURL(fileURLWithPath: path)
var playerItem = AVPlayerItem(URL: url)
var v = UIView(frame: f)
v.backgroundColor = UIColor.blackColor()
var player = AVPlayer(playerItem: playerItem)
var playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = f
v.layer.addSublayer(playerLayer)
player.play()
XCPShowView("View", view: v)
XCPSetExecutionShouldContinueIndefinitely(true)
答案 1 :(得分:6)
尝试在最后添加此项以保持游乐场运行
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
答案 2 :(得分:3)
感谢@Justin Levi Winter的回答,我更新了Swift3的代码,使用Xcode 8测试(此视频在时间轴中播放,但不在快速浏览中播放):
import AVFoundation
import PlaygroundSupport
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
let width = 568
let height = 320
let container = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
PlaygroundPage.current.liveView = container
PlaygroundPage.current.needsIndefiniteExecution = true
func playVideo(_ url: URL){
let f=CGRect(x: 0, y: 0, width: width, height: height)
let playerItem = AVPlayerItem(url: url)
let player=AVPlayer(playerItem: playerItem)
let playerLayer=AVPlayerLayer(player: player)
playerLayer.frame=f
container.layer.addSublayer(playerLayer)
PlaygroundPage.current.liveView = container
player.play()
}
playVideo(URL(string:"http://s3.amazonaws.com/vids4project/sample.mp4")!)
答案 3 :(得分:0)
对于Swift 5。*
在阅读了包括上述答案的几个答案之后,我编写了以下代码。 它可以工作,但问题播放器视图的放置有点偏离。我的意思是当它的框架的x和y值应该在左上角,但它不坐在那里。主要问题是如何实际编写url。
mounted()