如何嵌入不能在Iphone上启动外部播放器的YouTube视频?

时间:2013-04-05 21:14:52

标签: iphone youtube youtube-api embed

我正在尝试在我的应用程序中实现嵌入式Youtube视频。 我设法做到这一点的唯一方法是使用LBYouTubeViewHCYotubeParser等框架。根据我的阅读,他们反对Youtube TOS,因为他们基本上剥离了http的视频链接this

这确实可以在MPMoviePlayerController中播放而没有任何问题(并且不会离开应用程序)。

从我搜索的内容中有两个应用程序设法执行此操作VodioFrequency所以我想知道是否有一个特殊的sdk开发人员或我可能错过的联盟计划

从我也读过的内容Youtube工程师如果用youtube-api标记了这些问题,我希望你能清楚这一点。

我已经阅读过关于UIWebView实现的内容,但该场景实际上打开了一个我无法控制的外部视频播放器。

1 个答案:

答案 0 :(得分:0)

我环顾了一会儿,这就是我想出来的: 它涉及使用以下代码将youtube.html文件添加到项目中:

<html>
<head><style>body{margin:0px 0px 0px 0px;}</style></head>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
    // 2. This code loads the IFrame Player API code asynchronously.
    var tag = document.createElement('script');
    tag.src = "http://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    // 3. This function creates an <iframe> (and YouTube player)
    //    after the API code downloads.
    var player;
    function onYouTubePlayerAPIReady()
    {
    player = new YT.Player('player',
    {
      width: '640',
      height: '360',
      videoId: '%@',
      playerVars: {'autoplay' : 1, 'controls' : 0 , 'vq' : 'hd720', 'playsinline' : 1, 'showinfo' : 0, 'rel' : 0, 'enablejsapi' : 1, 'modestbranding' : 1},
      events:
        {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
        }
    });
    }

    // 4. The API will call this function when the video player is ready.
    function onPlayerReady(event)
    {
        event.target.playVideo();
    }

    // 5. The API calls this function when the player's state changes.
    //    The function indicates that when playing a video (state=1),
    //    the player should play for six seconds and then stop.
    var done = false;
    function onPlayerStateChange(event)
    {
    if (event.data == YT.PlayerState.ENDED) 
        {
            window.location = "callback:anything"; 
        };
    }
    function stopVideo() 
    {
        player.stopVideo();
        window.location = "callback:anything";
    }
    function getTime()
    {
        return player.getCurrentTime();
    }
    function getDuration()
    {
        return player.getDuration();
    }
    function pause()
    {
        player.pauseVideo();
    }
    function play()
    {
        player.playVideo();
    }
</script>
</body>
</html>

此外,您还必须创建一个UiWebView子类,它也是UIWebViewDelegate的委托

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self == nil) return nil;

    self.mediaPlaybackRequiresUserAction = NO;
    self.delegate = self;
    self.allowsInlineMediaPlayback = TRUE;
    self.userInteractionEnabled = FALSE;
    return self;
}

- (void)loadVideo:(NSString *)videoId
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"YouTube" ofType:@"html"];
    //    if (filePath == nil)

    NSError *error;
    NSString *string = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
    // TODO: error check

    string = [NSString stringWithFormat:string, videoId];

    NSData *htmlData = [string dataUsingEncoding:NSUTF8StringEncoding];
    //    if (htmlData == nil)

    NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *targetPath = [documentsDirectoryPath stringByAppendingPathComponent:@"youtube2.html"];
    [htmlData writeToFile:targetPath atomically:YES];

    [self loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:targetPath]]];
    File = 0;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[[request URL] scheme] isEqualToString:@"callback"])
    {
        Playing = FALSE;

        NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *targetPath = [documentsDirectoryPath stringByAppendingPathComponent:@"youtube2.html"];
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:targetPath error:&error];       
    }
    return YES;
}

基本上它会创建一个UIWebView并加载youtube.html文件中的代码。因为youtube.html是静态的,我需要加载某个id我在文件夹youtube2.html中动态创建一个副本,我在其中添加了字符串id。

整个事情是[self loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:targetPath]]];但是工作但是从字符串加载NSUrlRequest不会。

您在html文件中看到的Javascript函数用于控制视频。如果您需要访问时间或完整的持续时间,您可以这样得到它们:

float VideoDuration = [[YT_WebView stringByEvaluatingJavaScriptFromString:@"getDuration()"] floatValue];
float VideoTime = [[YT_WebView stringByEvaluatingJavaScriptFromString:@"getTime()"] floatValue];