Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play a video with AVPlayer in Swift Playground?

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.

like image 428
ohsnapy Avatar asked Sep 20 '14 05:09

ohsnapy


3 Answers

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
like image 108
Justin Levi Winter Avatar answered Oct 06 '22 13:10

Justin Levi Winter


Try adding this at the end to keep the playground running

import XCPlayground
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
like image 28
Gene De Lisa Avatar answered Oct 06 '22 11:10

Gene De Lisa


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")!)
like image 5
Bill Chan Avatar answered Oct 06 '22 12:10

Bill Chan