AVPlayerViewController

AVPlayerViewController

这是一个基本的playMe函数,调用AVPlayer,可通过AppleTV通过Swift播放MP3,MP4或Wav。如何将其与AVPlayerViewController结合-即如何使playMe(“ video”,“ mp4”)在AVPlayerViewController中播放,在Main.storyboard和在GUI和Swift代码中使用AVPlayerViewController?

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

最佳答案

一种实现方法是将AVPlayerViewController子类化。 AVPlayerViewController具有名为AVPlayerplayer属性。 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()
        }
    }

}

关于swift - Swift/AppleTV4:如何将AVPlayer函数连接到AVPlayerViewController?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34525804/

10-13 05:45