Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play video file from documentdirectory using avplayer

Tags:

ios

avplayer

I am creating video player application in ios,if i store mp4 file in bundle resource or if i stream url it is working fine but if i store a file in document direcory and i am trying to play with avplayer it is not playing should i handle differently with offline file in document directory

code:

let fileManager = FileManager()
        let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/myvideo.mp4"))
   self.playVideo(filePath: destinationURLForFile.path)


   func playVideo(filePath:String)
    {
        var playerItem = AVPlayerItem.init(url:URL.init(string: filePath)!)

        var player = AVPlayer(playerItem: playerItem)
        var playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.view.frame
        self.view.layer.addSublayer(playerLayer)
        player.play()

    }
like image 228
skyshine Avatar asked Dec 24 '22 14:12

skyshine


1 Answers

Try this, written in Swift 3.0,

let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let path = docsurl.appendingPathComponent("myvideo.mp4")
playVideo(filePath: path)

func playVideo(filePath:String)
{
    var playerItem = AVPlayerItem(url: URL(fileURLWithPath: filePath)
    var player = AVPlayer(playerItem: playerItem)
    var playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    self.view.layer.addSublayer(playerLayer)
    player.play()

}
like image 105
AshokPolu Avatar answered Apr 28 '23 15:04

AshokPolu