Ios Swift 3在页面加载后自动播放视频

时间:2017-08-25 07:39:29

标签: ios swift3

我目前正在使用' AVKit'和' AVFoundation'通过我的应用程序启用视频播放,但我只能通过点击按钮启动视频。但我目前面临的问题是,在我们在iOS设备上启动应用程序后立即尝试制作自动功能,例如播放视频片段。

override func viewDidLoad() 
{ 
  super.viewDidLoad()
  self.playingVideo()
  self.nowPlaying(self)
}

@IBAction func nowPlaying(_ sender: Any) 
{
  self.present(self.playerController, animated: true, completion:{
  self.playerController.player?.play()                
})

编译完成后,系统打印出来:

  

警告:尝试显示其视图不在窗口层次结构中!

1 个答案:

答案 0 :(得分:0)

请尝试使用以下工作代码。

import AVFoundation
import UIKit

class SomeViewController: UIViewController {

    func openVideo() {
        let playerController = SomeMediaPlayer()
        playerController.audioURL = URL(string: "Some audio/video url string")
        self.present(playerController, animated: true, completion: nil)
    }
}

class SomeMediaPlayer: UIViewController {
    public var audioURL:URL!
    private var player = AVPlayer()
    private var playerLayer: AVPlayerLayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.playerLayer = AVPlayerLayer(player: self.player)
        self.view.layer.insertSublayer(self.playerLayer, at: 0)
        let playerItem = AVPlayerItem(url: self.audioURL)
        self.player.replaceCurrentItem(with: playerItem)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.player.play()
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.playerLayer.frame = self.view.bounds
    }

    // Force the view into landscape mode if you need to
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        get {
            return .landscape
        }
    }
}