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

Eya*_*yal 34 youtube objective-c youtube-api uiwebview ios

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

所以我有一个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];
}
Run Code Online (Sandbox Code Playgroud)

问题:

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

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

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

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

Eya*_*yal 49

显然问题是使用nil base url,当我将它更改为resourceURL时,autoplay工作.

[self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];  
Run Code Online (Sandbox Code Playgroud)

自动播放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]];
}
Run Code Online (Sandbox Code Playgroud)

  • 弄清楚了!确保`UIWebView`上的`mediaPlaybackRequiresUserAction`属性设置为`NO`(默认为'YES`)! (7认同)

JAL*_*JAL 14

这里的关键是设置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)
Run Code Online (Sandbox Code Playgroud)

  • @ryantxr,那些小调整是什么.请分享. (3认同)

小智 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
Run Code Online (Sandbox Code Playgroud)