如何在UIWebView中自动播放YouTube视频

时间:2013-03-30 10:59:17

标签: ios objective-c youtube uiwebview youtube-api

我在这里看到很多关于这个问题的帖子,但仍然无法找到这个问题的完美答案。

所以我有一个tableview,每个单元格里面都有一个播放按钮。当用户点按播放按钮时,我会向此单元格添加UIWebView,然后播放YouTube视频。

static NSString *youTubeVideoHTML = @"<html>\
    <body style=\"margin:0;\">\
        <iframe class=\"youtube-player\" type=\"text/html\" width=\"%0.0f\" height=\"%0.0f\" src=\"http://www.youtube.com/embed/%@\" frameborder=\"0\">\
        </iframe>\
    </body>\
    </html>";


- (void)playVideoWithId:(NSString *)videoId {
    NSString *html = [NSString stringWithFormat:youTubeVideoHTML, self.frame.size.width, self.frame.size.height, videoId];

    [self loadHTMLString:html baseURL:nil];
}

问题:

此代码实际上并不像我想要的那样播放视频,只是启动YouTube播放器并使用YouTube红色播放按钮进行显示。只有当用户点击红色按钮时,视频才会开始播放 因此,用户必须点击两个按钮,直到视频开始 - 而不是最好的用户体验......

就像我说的那样,我看到很多关于这个问题的帖子,有些根本不起作用,有些作品但有一些问题让我感到困扰。

我找到的一个工作解决方案是@ilias的this post,他展示了如何使用文件加载HTML(而不是像我这样的字符串),这个问题的问题是对于我播放的每个视频,我需要:
加载htm文件 - &gt;将视频ID嵌入其中 - &gt;将文件写入光盘 - &gt;只有现在我才能播放视频。

奇怪的是,此解决方案仅在您从文件加载Web视图请求时起作用,如果我尝试从等于文件内容的字符串加载请求,则该方法无效。

5 个答案:

答案 0 :(得分:49)

显然问题出在nil base url上,当我将它更改为resourceURL时,自动播放工作正常。

[self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];  

自动播放youtube视频的完整代码(此代码主要基于this post我只是将其更改为从字符串而不是文件加载):

static NSString *youTubeVideoHTML = @"<!DOCTYPE html><html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%0.0f', height:'%0.0f', videoId:'%@', events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";  

- (void)playVideoWithId:(NSString *)videoId {
    NSString *html = [NSString stringWithFormat:youTubeVideoHTML, self.frame.size.width, self.frame.size.height, videoId];

    [self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
}

答案 1 :(得分:14)

此处的关键是在您的iFrame播放器中设置playsinline=1,为allowsInlineMediaPlayback = true设置mediaPlaybackRequiresUserAction = falseUIWebView。这是我在Swift中的实现:

// Set up your UIWebView
let webView = UIWebView(frame: self.view.frame) // or pass in your own custom frame rect

self.view.addSubview(webView)
self.view.bringSubviewToFront(webView)

// Set properties
webView.allowsInlineMediaPlayback = true
webView.mediaPlaybackRequiresUserAction = false

// get the ID of the video you want to play
let videoID = "zN-GGeNPQEg" // https://www.youtube.com/watch?v=zN-GGeNPQEg

// Set up your HTML.  The key URL parameters here are playsinline=1 and autoplay=1
// Replace the height and width of the player here to match your UIWebView's  frame rect
let embededHTML = "<html><body style='margin:0px;padding:0px;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}function onPlayerReady(a){a.target.playVideo();}</script><iframe id='playerId' type='text/html' width='\(self.view.frame.size.width)' height='\(self.view.frame.size.height)' src='http://www.youtube.com/embed/\(videoID)?enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'></body></html>"

// Load your webView with the HTML we just set up
webView.loadHTMLString(embededHTML, baseURL: NSBundle.mainBundle().bundleURL)

答案 2 :(得分:8)

这是完整的解决方案:

//
//  S6ViewController.m
//  
//
//  Created by Ökkeş Emin BALÇİÇEK on 11/30/13.
//  Copyright (c) 2013 Ökkeş Emin BALÇİÇEK. All rights reserved.
//

#import "S6ViewController.h"

@interface S6ViewController ()

@end

@implementation S6ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self playVideoWithId:@"sLVGweQU7rQ"];

}




- (void)playVideoWithId:(NSString *)videoId {

     NSString *youTubeVideoHTML = @"<html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'768', height:'1024', videoId:'sLVGweQU7rQ', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";

    NSString *html = [NSString stringWithFormat:youTubeVideoHTML, videoId];

    UIWebView *videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
    videoView.backgroundColor = [UIColor clearColor];
    videoView.opaque = NO;
    //videoView.delegate = self;
    [self.view addSubview:videoView];

    videoView.mediaPlaybackRequiresUserAction = NO;

    [videoView loadHTMLString:youTubeVideoHTML baseURL:[[NSBundle mainBundle] resourceURL]];
}

@end

答案 3 :(得分:4)

- (void)playVideoWithId:(NSString *)videoId {

NSString *youTubeVideoHTML = @"<html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'768', height:'1024', videoId:'%@', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";

NSString *html = [NSString stringWithFormat:youTubeVideoHTML, videoId];

UIWebView *videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
videoView.backgroundColor = [UIColor clearColor];
videoView.opaque = NO;
//videoView.delegate = self;
[self.view addSubview:videoView];

videoView.mediaPlaybackRequiresUserAction = NO;

[videoView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
}

我对上面的代码进行了一些修正。

答案 4 :(得分:2)

使用以下代码在UIWebView

中播放YouTube视频

这里我们需要&#34;嵌入链接&#34; :

  • 只需在浏览器中打开youtube链接
  • 即可
  • 右键点击视频
  • 选择选项&#34;获取嵌入代码&#34;
  • 您将获得类似 -

    的输出
    <iframe width="640" height="390" src="https://www.youtube.com/embed/xtNXZA4XMBY" frameborder="0" allowfullscreen></iframe>
    
  • 复制&#34; src&#34;中的链接字段,这是你的嵌入链接

    现在只需将此嵌入链接放在&#34; YOU_TUBE LINK&#34;在以下代码中:

    NSString *htmlString = [NSString stringWithFormat:@"<html><head><meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = yes, width = 320\"/></head><body style=\"background:#00;margin-top:0px;margin-left:0px\"><div><object width=\"320\" height=\"480\"><param name=\"movie\" value=\"YOUTUBE_LINK\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"YOUTUBE_LINK\"type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"320\" height=\"480\"></embed></object></div></body></html>"];
    
    [self.webView_youTube loadHTMLString:htmlString baseURL:nil];