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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15717754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:57:15  来源:igfitidea点击:

How to autoplay a YouTube video in a UIWebView

iosobjective-cyoutubeuiwebviewyoutube-api

提问by Eyal

I have seen a lot of posts in here about this issue, but still couldn't find a perfect answer for this problem.

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

So I have a tableview, and each cell has a play button inside it. When the user tap the play button, I add a UIWebViewto this cell, and play a YouTube video.

所以我有一个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];
}

The problem:

问题:

This code doesn't actually play the video like I want, it just initiate the YouTube player and show it with the YouTube red play button. Only when user tap the red button, the video will start playing.
So user has to tap two buttons until the video starts - not the best user experience...

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

Like I said I saw many posts about this issue, some not work at all, and some works but with some issues that bugs me.

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

One of the working solutions I found was in this postby @ilias, he shows how to get this working with loading the HTML from a file (instead of a string like I do), problem with this approche is that for every video I play I need to:
load the htm file -> embed the video Id in it -> write the file to disc -> only now I can play the video.

我在@ilias 的这篇文章中找到了一个可行的解决方案,他展示了如何通过从文件(而不是像我这样的字符串)加载 HTML 来实现这一点,这种方法的问题是对于我播放的每个视频我需要:
加载 htm 文件 -> 在其中嵌入视频 ID -> 将文件写入光盘 -> 现在我可以播放视频。

Strange thing is that this solution only work when you load the web view request from a file, if I try to load the request from a string equal to the file content, that doesn't work.

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

回答by Eyal

Apparently the problem was with the nil base url, when I changed it to resourceURL the autoplay worked.

显然问题出在 nil 基本 url 上,当我将其更改为 resourceURL 时,自动播放起作用了。

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

The full code for autoplay youtube videos (again this code mostly based on this postI just changed it to load from a string instead of a file):

自动播放 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]];
}

回答by JAL

The key here is to set playsinline=1in your iFrame player, and allowsInlineMediaPlayback = trueand mediaPlaybackRequiresUserAction = falsefor your UIWebView. Here's my implementation in Swift:

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

回答by okkesemin

Here is full solution:

这是完整的解决方案:

//
//  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

回答by Vannian

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

I did some correction to the code above.

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

回答by nilam_mande

Use following code to play a youtube video in the UIWebView

使用以下代码在 UIWebView

Here we required "embed link" :

这里我们需要“嵌入链接”:

  • 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];
    
  • 只需在浏览器中打开您的 YouTube 链接
  • 右击视频
  • 选择选项“获取嵌入代码”
  • 你会得到这样的输出 -

    <iframe width="640" height="390" src="https://www.youtube.com/embed/xtNXZA4XMBY" frameborder="0" allowfullscreen></iframe>
    
  • 复制“src”字段中的链接,这是您的嵌入链接

    现在只需将此嵌入链接放在以下代码中的“YOU_TUBE LINK”位置:

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