Reputation: 946
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
- i.e., 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()
}
Upvotes: 0
Views: 698
Reputation: 301
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()
}
}
}
Upvotes: 1