简体   繁体   中英

Swift/AppleTV4: How to connect AVPlayer function to AVPlayerViewController?

Here is a rudimentary playMe function calling AVPlayer , playing a MP3, MP4 or Wav via Swift with AppleTV. How do I combine this with the AVPlayerViewController - ie, how do I make the playMe("video", "mp4") play inside an AVPlayerViewController , what are the required steps to make a connection between the Main.storyboard and the AVPlayerViewController, in the GUI and in the Swift code?

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

One way you could do this is by subclassing AVPlayerViewController . AVPlayerViewController has an AVPlayer property named player . A subclass of AVPlayerViewController might look something like this:

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

}

This implementation would show the default playback controls and would work out of the box with the Siri remote.

Here is the code to do this via a button press using 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()
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM