Swift:AVPlayer播放视频显示此错误:[AVOutputContext]警告:AVF上下文不可用于sharedAudioPresentationContext

时间:2017-10-06 19:35:45

标签: ios swift avplayer avplayerviewcontroller avplayerview

我正在尝试播放捆绑目录中的视频但我收到此错误:

  

video [29054:2968406] [MediaRemote] [AVOutputContext]警告:AVF   上下文不可用于sharedAudioPresentationContex

这是我的实施:

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()

    }

你们中的任何人都知道我做错了什么吗?我非常感谢你的帮助。

3 个答案:

答案 0 :(得分:0)

我对设备上存储的mp4文件有类似的问题,该问题通过在文件路径前添加“ file://”而得以解决

 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
    }

受到this post

的启发

答案 1 :(得分:0)

这是我的实现。对我来说很好。

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()
    }
}
}

希望这对您有帮助!

答案 2 :(得分:-5)

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()
        }
    }