javascript YouTube API 不适用于 iPad / iPhone / 非 Flash 设备
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8972726/
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
YouTube API not working with iPad / iPhone / non-Flash device
提问by SparrwHawk
This piece of code works great in DESKTOP browsers (code courtesy of @Rob-W), click the thumbnail and the adjacent video will start playing, using YouTube's API.
这段代码在桌面浏览器中效果很好(代码由@Rob-W 提供),单击缩略图,相邻的视频将开始播放,使用 YouTube 的 API。
HTML
HTML
<div id="tabs2">
<div>
<img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'>
<iframe id="frame1" width="640" height="390" frameborder="0" title="YouTube video player"type="text/html"src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe>
</div>
<div>
<img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'>
<iframe id="frame2" width="640" height="390" frameborder="0" title="YouTube video player"type="text/html"src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe>
</div>
</div>
CSS
CSS
#tabs2 div {
position: relative;
}
/* For security reasons, an element cannor be placed over a frame */
/*.thumb {
position: absolute;
}*/
.play {
border: 3px solid red;
}
JS
JS
function getFrameID(id) {
var elem = document.getElementById(id);
if (elem) {
if (/^iframe$/i.test(elem.tagName)) return id; //Frame, OK
// else: Look for frame
var elems = elem.getElementsByTagName("iframe");
if (!elems.length) return null; //No iframe found, FAILURE
for (var i = 0; i < elems.length; i++) {
if (/^https?:\/\/(?:www\.)?youtube(?:-nocookie)?\.com(\/|$)/i.test(elems[i].src)) break;
}
elem = elems[i]; //The only, or the best iFrame
if (elem.id) return elem.id; //Existing ID, return it
// else: Create a new ID
do { //Keep postfixing `-frame` until the ID is unique
id += "-frame";
} while (document.getElementById(id));
elem.id = id;
return id;
}
// If no element, return null.
return null;
}
// Define YT_ready function.
var YT_ready = (function() {
var onReady_funcs = [],
api_isReady = false;
/* @param func function Function to execute on ready
* @param func Boolean If true, all qeued functions are executed
* @param b_before Boolean If true, the func will added to the first
position in the queue*/
return function(func, b_before) {
if (func === true) {
api_isReady = true;
for (var i = 0; i < onReady_funcs.length; i++) {
// Removes the first func from the array, and execute func
onReady_funcs.shift()();
}
}
else if (typeof func == "function") {
if (api_isReady) func();
else onReady_funcs[b_before ? "unshift" : "push"](func);
}
}
})();
// This function will be called when the API is fully loaded
function onYouTubePlayerAPIReady() {
YT_ready(true)
}
var players = {};
//Define a player storage object, to enable later function calls,
// without having to create a new class instance again.
YT_ready(function() {
$(".thumb + iframe[id]").each(function() {
var identifier = this.id;
var frameID = getFrameID(identifier);
if (frameID) { //If the frame exists
players[frameID] = new YT.Player(frameID, {
events: {
"onReady": createYTEvent(frameID, identifier)
}
});
}
});
});
// Returns a function to enable multiple events
function createYTEvent(frameID, identifier) {
return function (event) {
var player = players[frameID]; // player object
var the_div = $('#'+identifier).parent();
the_div.children('.thumb').click(function() {
var $this = $(this);
$this.fadeOut().next().addClass('play');
if ($this.next().hasClass('play')) {
player.playVideo();
}
});
}
}
// Load YouTube Frame API
(function(){ //Closure, to not leak to the scope
var s = document.createElement("script");
s.src = "http://www.youtube.com/player_api"; /* Load Player API*/
var before = document.getElementsByTagName("script")[0];
before.parentNode.insertBefore(s, before);
})();
The problem is that it fails to play on iOS devices (because of the lack of Flash player, I think, it just hangs).
问题是它无法在 iOS 设备上播放(因为缺少 Flash 播放器,我认为,它只是挂起)。
I can force it to play by tapping the video once more, which prompts it to play using QuickTime.
我可以通过再次点击视频来强制它播放,这会提示它使用 QuickTime 播放。
But how do I get it to play with QuickTime automatically?
但是如何让它自动与 QuickTime 一起播放?
回答by Aaron
I'm sorry to say this is not possible in iOS. According to Apple's documentation,
我很遗憾地说这在 iOS 中是不可能的。根据苹果的文档,
"...embedded media cannot be played automatically in Safari on iOS - the user always initiates playback."
“...嵌入的媒体无法在 iOS 上的 Safari 中自动播放 - 用户始终启动播放。”
The restriction is consistent regardless of network connection as it is both a bandwidth decision as well as a user experience decision.
无论网络连接如何,限制都是一致的,因为它既是带宽决策,也是用户体验决策。
Update, October, 2016: It's worth noting, now that iOS 10 is out and gaining significant market share, that people can leverage changes in the way video playback works on iOS 10 to get autoplay behavior. If the video has no audio tracks or the tag is muted, autoplay can be possible. More information is available in this webkit blog. The YouTube API may handle this nicely soon.
2016 年 10 月更新:值得注意的是,现在 iOS 10 已经推出并获得了可观的市场份额,人们可以利用 iOS 10 上视频播放方式的变化来获得自动播放行为。如果视频没有音轨或标签被静音,则可以自动播放。此 webkit 博客中提供了更多信息。YouTube API 很快就会很好地处理这个问题。
回答by Jeff Kelley
Beginning in iOS 4, UIWebView
has the mediaPlaybackRequiresUserAction
property. I can't tell if you're implementing this on the Web or in a native app, but setting that to NO
in a native app should allow auto play to work.
从 iOS 4 开始,UIWebView
具有该mediaPlaybackRequiresUserAction
属性。我不知道您是在 Web 上还是在本机应用程序中实现这一点,但是NO
在本机应用程序中将其设置为应该允许自动播放工作。
回答by Jeff Kelley
You can use the YouTube iFrame APIon iOS.
您可以在 iOS 上使用YouTube iFrame API。