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

34

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

所以我有一个表视图,每个单元格内都有一个播放按钮。当用户点击播放按钮时,我会向该单元格添加一个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提供,他展示了如何通过从文件(而不是像我所做的字符串)加载HTML来使其工作。但这种方法的问题在于对于我播放的每个视频,我都需要:
加载htm文件->将视频Id嵌入其中->将文件写入磁盘->现在才能播放视频。
奇怪的是,只有在从文件加载Web视图请求时,这个解决方案才有效,如果我尝试从与文件内容相等的字符串加载请求,则无法正常工作。

<iframe width=&quot;%f&quot; height=&quot;%f&quot; src=&quot;%@&quot; id='videoSize' frameborder=&quot;0&quot; autoplay=&quot;autoplay&quot; allowfullscreen></iframe> - Manu
在 iFrame 标签中包含自动播放。 - Manu
@Manohar,那个不起作用。 - Eyal
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStateDidChange:) name:@"MPAVControllerPlaybackStateChangedNotification" object:nil]; 一旦收到此通知,请让我知道。 - Manu
@Manohar:使用“委托”怎么样? - Abhishek Bedi
5个回答

49
显然,问题出在nil基础URL上,当我将其更改为resourceURL时,自动播放起作用了。
[self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];  

自动播放YouTube视频的完整代码(再次强调,这个代码主要基于这篇文章,我只是将其更改为从字符串加载而不是从文件加载):
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]];
}

7
搞定了!请确保在您的 UIWebView 上,mediaPlaybackRequiresUserAction 属性被设置为“NO”(默认为“YES”)! - Tim Arnold
1
它自动播放得很好,但在我的iPhone 5上(使用iOS6),视频仍然会以全屏(垂直)的形式打开Youtube视频。还有其他的想法吗?只是为了明确,小窗口首先出现,一旦开始播放就会变成全屏。 - Fluffhead
1
@Eyal 非常感谢,经过大量搜索,我找到了这个链接,并且它对我很有用。同时也欣赏你的提问方式。 :) - The iCoder
你好Eyal:当屏幕方向改变时,我该如何使播放器大小自动调整?目前,当页面未播放且方向改变时,视图大小不会改变。谢谢。 - Evelyn Loo
@Eyal,我们可以在启动时将其设置为全屏吗? - Qadir Hussain
显示剩余4条评论

14

关键在于在您的iFrame播放器中设置playsinline = 1,以及为您的UIWebView设置allowsInlineMediaPlayback = truemediaPlaybackRequiresUserAction = false。 这是我在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)

我按照你的代码完全操作,但它不会自动播放,自你写下这个答案以来有什么变化吗? - Kashif
@Kashif,你使用的是哪个平台/ios版本? - JAL
1
我认为自那个答案以来有些变化。我使用了这段代码,它正常显示,但不会自动播放。 - ryantxr
1
经过一些微调,它现在可以自动播放了。 :-) - ryantxr
3
@ryantxr,那些小改动是什么?请分享。 - pkc456
显示剩余4条评论

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

1
它是“html”参数,不是吗?:[videoView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]]; - Eugene Pinchuk

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

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


2

使用以下代码在UIWebView中播放YouTube视频:

这里需要“嵌入链接”:

  • Just open your youtube link in browser
  • Right click on video
  • Select option "Get embed code"
  • You'll get output like -

    <iframe width="640" height="390" src="https://www.youtube.com/embed/xtNXZA4XMBY" frameborder="0" allowfullscreen></iframe>
    
  • copy the link in "src" field, this is your embed link

    Now just put this embed link on the place of "YOU_TUBE LINK" in the following code:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接