0

这是一个基本的 playMe 函数调用AVPlayer,通过 Swift 和 AppleTV 播放 MP3、MP4 或 Wav。我如何将它与AVPlayerViewController- 即,如何让 playMe("video", "mp4") 在一个内部播放AVPlayerViewController,在 GUI 中建立 Main.storyboard 和 AVPlayerViewController 之间的连接所需的步骤是什么在 Swift 代码中?

func playMe(inputfile: String, inputtype: String) {
    let path = NSBundle.mainBundle().pathForResource(inputfile, ofType:inputtype)!
    let videoURL = NSURL(fileURLWithPath: path)
    let player = AVPlayer(URL: videoURL)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.bounds
    self.view.layer.addSublayer(playerLayer)
    player.play()
}
4

1 回答 1

1

你可以做到这一点的一种方法是子类化AVPlayerViewController. AVPlayerViewController有一个AVPlayer名为 的属性player。AVPlayerViewController 的子类可能看起来像这样:

import UIKit
import AVKit

class MyPlayerViewController: AVPlayerViewController {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        let path = NSBundle.mainBundle().pathForResource("myVideo", ofType:"mov")!
        let videoURL = NSURL(fileURLWithPath: path)
        player = AVPlayer(URL: videoURL)
    }

}

此实现将显示默认播放控件,并且可以使用 Siri 遥控器开箱即用。

下面是通过使用 prepareForSegue 按下按钮来执行此操作的代码:

import UIKit
import AVFoundation
import AVKit
let playerViewControllerSegue = "play";
class MyViewController: UIViewController {    
    @IBAction func playMovie(sender: UIButton) {
        self.performSegueWithIdentifier(playerViewControllerSegue, sender: self);
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == playerViewControllerSegue){
            let path = NSBundle.mainBundle().pathForResource("7second", ofType:"mp4")!
            let videoURL = NSURL(fileURLWithPath: path)
            let player = AVPlayer(URL: videoURL)
            let playerViewController = segue.destinationViewController as! AVPlayerViewController
            playerViewController.player = player
            playerViewController.player?.play()
        }
    }

}
于 2016-01-12T18:34:11.240 回答