jar*_*App 4 html javascript youtube-api reactjs
我使用 React 在页面上以正确的大小设置带有 youtube 视频的 iframe。一切正常,但对于手机而言,自动播放选项不起作用。
什么是有趣的页面,我有什么作为示例视频它完美无缺。
<iframe type="text/html" allowTransparency="true" height="100%" width="100%" preload="metadata" gesture="media" allow="encrypted-media" className="autoplay-iframe"
src={`https://www.youtube.com/embed/`+this.props.autoplay+`?autoplay=1&version=3&html5=1&hd=1&controls=0&loop=1&playlist=`+this.props.autoplay+`&playsinline=1&rel=0&showinfo=0&modestbranding=1&related=0&enablejsapi=1&origin=`+window.location.hostname} frameborder="0"></iframe>
Run Code Online (Sandbox Code Playgroud)
上面是我的 iframe 代码。我剪掉了 iframe 代码的一部分,但样式属性中只有样式。这对于自动播放并不重要。其他页面的最终 url 相同。我不知道为什么。任何提示我如何解决这个问题?
提前致谢。
小智 8
我能够播放 Youtube 视频(无需将其静音)。由于内联加载 Youtube 视频令 Google 及其新的 Core Web Vitals 感到不安,因此我们实现了一个缩略图占位符,当单击该占位符 (jQuery) 时,会使用 Youtube Iframe API 启动加载视频。我一开始也无法让它们自动播放。该问题通过让 API 嵌入 Iframe 得到解决——而不是事先将 iframe 放置到位。它可以在 iOS Safari、Chrome 和 Firefox 上自动播放。这对我有用:
文件准备好后:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady(yt_id, iframe_id, iframe_width, iframe_height){
player = new YT.Player(iframe_id, {
width: iframe_width,
height: iframe_height,
videoId: yt_id,
playerVars: { 'autoplay': 1, 'playsinline': 1 },
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
//event.target.mute();
event.target.setVolume(70);
event.target.playVideo();
}
Run Code Online (Sandbox Code Playgroud)
点击事件时:
$('.yt_video_link').on('click', function(e) {
e.preventDefault();
var div_id = $(this).attr('id');
var div_iframe = div_id + '_iframe';
var yt_id = $('#' + div_id).data('ytid');
$('#' + div_id + ' .yt_video_play').css('display', 'none');
onYouTubeIframeAPIReady(yt_id, div_iframe, 560, 315);
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<div id='yt_video_desktop' class='yt_video_link mobile_hide' data-ytid='<?=$yt_id?>'>
<div id='yt_video_desktop_player' class='yt_video'>
<img src='/catalog/images/yt_video_thumb_<?=$yt_id?>.jpg' alt='play desktop video' width='768' height='432' id='yt_video_desktop_iframe'>
</div>
<div class='yt_video_play'></div>
</div>
Run Code Online (Sandbox Code Playgroud)
您将无法实现此功能,因为它已对所有移动设备有意禁用。原因是为了用户保存蜂窝数据。这篇文章中也引用了这一点。
视频自动播放不起作用的原因很简单。该功能在移动设备的 iOS 和 Android 中都被故意禁用。这样做的原因是为了节省移动用户的钱。此类设备(尤其是移动电话)通常使用按带宽收费的数据连接。他们有数据限制,并且会产生费用。
以下 SO 帖子也支持此声明。