I am having trouble playing a video within a swift playground using AVPlayer.
Here's 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 as does nothing at all. My expectation is the 'v' variable should be showing the video. It seems to work outside the playground when I am connecting the avplayerlayer to a view from a storyboard.
The following should work if you drop it into a playground. Make sure to swap out the path: (Xcode 11 & Swift Playgrounds Mac & iOS)
import UIKit
import AVFoundation
import PlaygroundSupport
var playerFrame = CGRect(x: 0, y: 0, width: 500, height: 500)
guard let path = Bundle.main.path(forResource: "movie", ofType: "m4v") else {
fatalError("no movie found")
}
let url = URL(fileURLWithPath: path)
var playerItem = AVPlayerItem(url: url)
var playerView = UIView(frame: playerFrame)
playerView.backgroundColor = .black
var player = AVPlayer(playerItem: playerItem)
var playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = playerFrame
playerView.layer.addSublayer(playerLayer)
player.play()
PlaygroundPage.current.liveView = playerView
PlaygroundPage.current.needsIndefiniteExecution = true
Try adding this at the end to keep the playground running
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
Thanks of @Justin Levi Winter's answer and I had updated the code for Swift3, tested with Xcode 8 (This video plays in timeline, but not on the 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")!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With