I'm trying to play a video from bundle directory but I'm getting this error:

video[29054:2968406] [MediaRemote] [AVOutputContext] WARNING: AVF context unavailable for sharedAudioPresentationContex

This is my implementation:

import UIKit
import AVKit
import AVFoundation


class ViewController: UIViewController {
    var playerVC = AVPlayerViewController()
    var playerView = AVPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.playVideo()

    }


    func playVideo() {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as NSURL
        guard let fileURL  = documentsDirectory.appendingPathComponent("video.mp4") else{ return }
        self.playerView = AVPlayer(url:fileURL as URL)
        self.playerVC.player = playerView
        self.view.addSubview(self.playerVC.view)
        self.addChildViewController(self.playerVC)
        playerView.play()

    }

Any of you knows what I'm doing wrong?, I'll really appreciate your help.

3

There are 3 answers

1
Ayşe On
import UIKit
import AVKit
import AVFoundation


class ViewController: UIViewController {
    var playerVC = AVPlayerViewController()
    var playerView = AVPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

    }

override func viewDidAppear(_ animated: Bool) {

       let fileURL = NSURL(fileURLWithPath: "video.mp4")

        playerView = AVPlayer(url: fileURL as URL)
        playerViewController.player = playerView
        self.present(playerViewController, animated: true) {
        self.playerViewController.player?.play()
        }
    }
0
fazeel ahamed On

This is my implementation. It worked fine for me.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var playerViewController = AVPlayerViewController()
    var player = AVPlayer()


override func viewDidLoad() {
    super.viewDidLoad()
    self.playVideo()

}


func playVideo () {
   //creating your document folder url
    if let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        // creating your destination folder url
        let destinationUrl = documentsDirectoryURL.appendingPathComponent("video.mp4")
        self.player = AVPlayer(url: destinationUrl)
        self.playerViewController.player = self.player
        self.playerViewController.view.frame = self.view.frame
        self.view.addSubview(self.playerViewController.view)
        self.playerViewController.player?.play()
    }
}
}

Hope this helps you !!

0
dev On

I had similar issue with mp4 file stored on device which got fixed by prepending "file://" to the file path

 guard let strPath = Bundle.main.path(forResource: "demo", ofType: "mp4"), let url = URL(string: "file://\(strPath)") else {
        print("Umm, looks like an invalid URL!")
        return
    }

Inspired by this post