How do you play a local movie file with AVPlayer

Does anyone have example code in SWIFT on how to play a local movie file with AVPlayer?

Answered by Mav3r1ck in 57755022

Here's what I was looking for, hopfully this will help others later down the road.


var playerLayer: AVPlayer?

  let videoURL: NSURL = NSBundle.mainBundle().URLForResource("Para1_2", withExtension: "mp4")!
  let player = AVPlayer(URL: videoURL)
  playerLayer = AVPlayerLayer(player: player)
  playerLayer!.frame = self.view!.bounds
  self.view!.layer.addSublayer(playerLayer!)
  player.play()

The AVPlayer class method playerWithURL: will allow you to load a media file for playback. In terms of output, create an AVPlayerViewController assign the player properly, and present the view controller.


Also, take a look at the Mastering Modern Media Playback session from WWDC 2014 where we discuss how to use the above classes as well.

Accepted Answer

Here's what I was looking for, hopfully this will help others later down the road.


var playerLayer: AVPlayer?

  let videoURL: NSURL = NSBundle.mainBundle().URLForResource("Para1_2", withExtension: "mp4")!
  let player = AVPlayer(URL: videoURL)
  playerLayer = AVPlayerLayer(player: player)
  playerLayer!.frame = self.view!.bounds
  self.view!.layer.addSublayer(playerLayer!)
  player.play()

Hi,


How to close playerLayer when video has stopped playing?


i.e. Once AVPlayer stops playing local video player Layer should be removed from superLayer

If you no longer require video playback, then you could set the player property of the playerLayer to nil and remove the playerLayer from its superlayer.


But if you are looking to play a video modally, you should really look at AVPlayerViewController, as it includes the video playback control UI as well, in which case you present it like any other view controller.

Hi TidBits, Can you explain more on how to write code to dimiss AVPlayer?


I am currently using this code:


let videoURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("video-title", ofType:"mp4")!) 
let player = AVPlayer(URL: videoURL) 
let playerLayer = AVPlayerLayer(player: player) 
playerLayer.frame = self.view.bounds 
self.view.layer!.addSublayer(playerLayer) 
player.play()

If you are simply trying to play back a video full screen, I would recommend using AVPlayerViewController, which is part of the AVKit framework:


let videoURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("video-title", ofType:"mp4")!)
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
presentViewController(playerViewController, animated: true) { () -> Void in
     player.play()
}


This will modally present the playerViewController for full screen playback, triggering the playback to begin as part of that view controller presentation completion block.


To dismiss it, the user can either tap the "Done" button, or you can pause playback on the player, and then dismiss the playerViewController like you would any other view controller, using dismissViewControllerAnimated(flag: Bool, completion: (() -> Void)?)

Hi, Is this code will work with Cocoa? As I am developing OSX app.


I am getting error at line 3: Use of unresolved identifier 'AVPlayerViewController'


I have already imported Cocoa, AVFoundation & AVKit

On OS X, the player class is AVPlayerView:

https://developer.apple.com/library/mac/documentation/AVKit/Reference/AVPlayerView_Class/index.html#//apple_ref/occ/cl/AVPlayerView


In this case, it's simply an NSView subclass, so you can add or remove it as a subview as required, like you would any other view. The above example was for iOS/tvOS.

Hi TidBits,


I am using this code as intsructed by fellow community member but it is not working...


let videoURL = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("video-title", ofType:"mp4")!) 
let player = AVPlayer(URL: videoURL) 
let playerLayer = AVPlayerLayer(player: player) 
playerLayer.frame = self.view.bounds 
self.view.layer!.addSublayer(playerLayer) 
player.play() 
let duration = player.currentItem!.duration 
timeObserver = player.addBoundaryTimeObserverForTimes([NSValue(CMTime: duration)], queue: nil) {[weak self] in 
  playerLayer.removeFromSuperlayer() 
        self!.timeObserver = nil
}


PlayerLayer doesn't get dismiss after it's finish playing video.

I had a similar problem using this method:


var timer = Timer()

private func playVideo(from file:String) {
    let file = file.components(separatedBy: ".")
   
    guard let path = Bundle.main.path(forResource: file[0], ofType:file[1]) else {
        debugPrint( "\(file.joined(separator: ".")) not found")
        return
    }
    let player = AVPlayer(url: URL(fileURLWithPath: path))
   
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.bounds
    self.view.layer.addSublayer(playerLayer)
    player.play()
   
    let duration = player.currentItem!.duration.seconds
    timer = Timer.scheduledTimer(withTimeInterval: duration, repeats: false, block: { (timer) in
        player.pause()
        playerLayer.removeFromSuperlayer()
        timer.invalidate()
    })
}

Hi TidBits,


Do you know how to programmatically call another function when the user tapped the "Done" button of the view controller?


Thanks,


Wendell

How do you play a local movie file with AVPlayer
 
 
Q