How to play YouTube content on tvOS

2019-01-07 05:57发布

问题:

How would one play a YouTube video on Apple tvOS?

YouTube's embed feature works in iOS 9 as the OS has a UIWebView we can embed it into. The new tvOS does not include a UIWebView so I cannot see a way to embed the YouTube video.

回答1:

UIWebView and MPMoviePlayerController are not available for tvOS. Our next option is to use AVPlayer to play YouTube videos.

AVPlayer cannot play a YouTube video from a standard YouTube URL, ie. https://www.youtube.com/watch?v=8To-6VIJZRE. It needs a direct URL to the video file. Using HCYoutubeParser we can accomplish exactly that. Once we have the URL we need, we can play it with our AVPlayer like so:

NSString *youTubeString = @"https://www.youtube.com/watch?v=8To-6VIJZRE";
NSDictionary *videos = [HCYoutubeParser h264videosWithYoutubeURL:[NSURL URLWithString:youTubeString]];
NSString *urlString = [NSString stringWithFormat:@"%@", [videos objectForKey:@"medium"]];
AVAsset *asset = [AVAsset assetWithURL:[NSURL URLWithString:urlString]];

AVPlayerItem *avPlayerItem = [[AVPlayerItem alloc]initWithAsset:asset];
AVPlayer *videoPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:videoPlayer];
avPlayerLayer.frame = playerView.layer.bounds;
[playerView.layer addSublayer:avPlayerLayer];

[videoPlayer play];

Note that this is NOT allowed under YouTube's TOS. Use it at your own risk. Your app may stop working at any point if YouTube notices you are not following the TOS or if YouTube changes the embed code it generates.



回答2:

Swift 2.0 version of Daniel Storm's answer:

let youTubeString : String = "https://www.youtube.com/watch?v=8To-6VIJZRE"
let videos : NSDictionary = HCYoutubeParser.h264videosWithYoutubeURL(NSURL(string: youTubeString))
let urlString : String = videos["medium"] as! String
let asset = AVAsset(URL: NSURL(string: urlString)!)

let avPlayerItem = AVPlayerItem(asset:asset)
let avPlayer = AVPlayer(playerItem: avPlayerItem)
let avPlayerLayer  = AVPlayerLayer(player: avPlayer)
avPlayerLayer.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height);
self.view.layer.addSublayer(avPlayerLayer)
avPlayer.play()


回答3:

XCDYouTubeKit has been a popular way to directly play a YouTube video on iOS for a while, and the developer recently updated it to support the new AppleTV.

Here's the code from the Objective-C example:

AVPlayerViewController *playerViewController = [AVPlayerViewController new];
[self presentViewController:playerViewController animated:YES completion:nil];

__weak AVPlayerViewController *weakPlayerViewController = playerViewController;
[[XCDYouTubeClient defaultClient] getVideoWithIdentifier:playlistItem.snippet.resourceId.videoId completionHandler:^(XCDYouTubeVideo * _Nullable video, NSError * _Nullable error) {
    if (video)
    {
        NSDictionary *streamURLs = video.streamURLs;
        NSURL *streamURL = streamURLs[XCDYouTubeVideoQualityHTTPLiveStreaming] ?: streamURLs[@(XCDYouTubeVideoQualityHD720)] ?: streamURLs[@(XCDYouTubeVideoQualityMedium360)] ?: streamURLs[@(XCDYouTubeVideoQualitySmall240)];
        weakPlayerViewController.player = [AVPlayer playerWithURL:streamURL];
        [weakPlayerViewController.player play];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}];

Swift example here.



回答4:

Sadly, even an Apple Staff person echoed the “negative” on this. From an Apple Developer Forums thread on the topic:

There is no support for WebViews on tvOS, and so an iframe implementation will not work. TVML does not offer this capability.



回答5:

As an addition to Daniel Storm's answer, you can also achieve this with the new TVML language using the code:

<lockup videoURL="http://mp4-url.mp4">
<img src="video thumbnail.jpg" />
</lockup>

(for this to work you'll need the direct video file (mp4) which also is not allowed by the Youtube TOS)

EDIT, found also the .JS solution: How do I play a video on tvOS for Apple TV?



回答6:

I used this one https://cocoapods.org/pods/youtube-parser

Youtube.h264videosWithYoutubeURL(testURL) { (videoInfo, error) -> Void in
    if let videoURLString = videoInfo?["url"] as? String,
         videoTitle = videoInfo?["title"] as? String {
             print("\(videoTitle)")
             print("\(videoURLString)")
             self.playVideo(videoURLString)
    }
}