用Swift 2.0播放AVPlayer

时间:2016-05-22 20:19:02

标签: ios swift avplayer playback

我在播放视频方面遇到问题。我想要的只是在显示启动图像后播放视频。我按照这个(https://www.youtube.com/watch?v=iYATp9--VIM)教程,但是当我模拟时,我收到了一个空白屏幕。

以下是代码:

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet var videoView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupView()  
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func setupView() {
        let path = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("streetview", ofType: "mov")!)

        let player = AVPlayer(URL:path)

        let newLayer = AVPlayerLayer(player: player)
        newLayer.frame = self.videoView.frame
        self.videoView.layer.addSublayer(newLayer)
        newLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

        player.play()
    }
}

如果可以,请帮助我!

1 个答案:

答案 0 :(得分:0)

如果你只是一个空白的黑屏,通常会指出视频来源的问题。我会检查你是否正确拼写了你的文件的名称,它肯定是一个.mov文件。

我使用此代码启动AVPlayer并播放我的视频。它播放来自互联网的URL的视频。我把它放在我的按钮功能中,所以当用户按下我的播放按钮时会发生这种情况:

let videoURL = NSURL(string: "YOUR URL") {
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {

    playerViewController.player!.play()

}

我可以在Swift 2.0中确认这对我有用