Play video from AVPlayer in Swift Playground?

I'm having trouble playing videos on a fast playground using AVPlayer.

Here is my code.

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

Any suggestions? The code does nothing at all. My expectation is that the variable 'v' should show the video. It seems to work off-site when I connect avplayerlayer to the view from the storyboard.

+5
source share
3 answers

The following should work if you drop it on the playing field. Be sure to change the path: (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) 
+7
source

Try adding this at the end to support the playground.

 import XCPlayground XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true) 
+6
source

Thanks @Justin Levi Winter answer, and I updated the code for Swift3 tested with Xcode 8 (This video plays in the timeline, but not on Quick Look):

 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")!) 
0
source

Source: https://habr.com/ru/post/1203022/


All Articles