如何在 tvOS 上播放 YouTube 内容 [英] How to play YouTube content on tvOS

查看:129
本文介绍了如何在 tvOS 上播放 YouTube 内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Apple tvOS 上播放 YouTube 视频?

How would one play a YouTube video on Apple tvOS?

YouTube 的嵌入功能适用于 iOS 9,因为操作系统有一个 UIWebView,我们可以将其嵌入.新的 tvOS 不包含 UIWebView,所以我看不到嵌入 YouTube 视频的方法.

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.

推荐答案

UIWebViewMPMoviePlayerController 不适用于 tvOS.我们的下一个选择是使用 AVPlayer 播放 YouTube 视频.

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

AVPlayer 无法从标准 YouTube URL 播放 YouTube 视频,即.https://www.youtube.com/watch?v=8To-6VIJZRE.它需要视频文件的直接 URL.使用 HCYoutubeParser 我们可以做到这一点.一旦我们有了我们需要的 URL,我们就可以像这样使用 AVPlayer 播放它:

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];

请注意,YouTube 的服务条款不允许允许这样做.使用风险自负.如果 YouTube 发现您没有遵守 TOS 或者 YouTube 更改了它生成的嵌入代码,您的应用可能随时停止工作.

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.

这篇关于如何在 tvOS 上播放 YouTube 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆