使用 YouTube IFrame Player API
https://developers.google.com/youtube/player_parameters?hl=zh-cn
自己的需求:多个视频同一页播放并且YOUTUBE播放器内需要展现出该频道内的所有视频列表
主要代码:
后台填入视频ID和列表ID传到前端
<span class="open-video" data-id="{$value.Youtube_id}" data-listid="{$value.Youtube_listid}"><a href="javascript:void(0);">Youtube</a></span>
播放器HTML代码:
弹出层
<div class="video">
<div class="video-title">YOUTUBE VIDEO PLAY<span><a href="javascript:void(0);" class="close-video">Close</a></span></div>
<video id="my-video"></video>
</div>
script代码基本复制demo的
只是做了个动态获取视频ID和列表ID 然后触发播放
var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function onYouTubeIframeAPIReady() { player = new YT.Player('my-video', { height: '550', '1000', autoplay:0, videoId: '3-__8xjeckg', controls:1, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } // 4. The API will call this function when the video player is ready. function onPlayerReady(event) { event.target.playVideo(); } // 5. The API calls this function when the player's state changes. // The function indicates that when playing a video (state=1), // the player should play for six seconds and then stop. var done = false; function onPlayerStateChange(event) { if (event.data == YT.PlayerState.PLAYING && !done) { setTimeout(stopVideo, 6000); done = true; } } function stopVideo() { player.stopVideo(); } $('.close-video').click(function(){ player.stopVideo(); $('.video').hide(); $('.video-bg').hide(); }); $('.open-video').click(function(){ //console.log($(this).data('listid')); player.loadVideoById($(this).data('listid'), 5, "large"); player.loadPlaylist ({listType:'playlist', list:$(this).data('listid')}); player.playVideo(); $('.video').show(); $('.video-bg').show(); });
整个使用过程没问题,就是获取频道播放列表这里有个巨坑,刚好踩到了
最后查到
这里说到
调用loadPlaylist 有两种方式一种是直接传参数,另一种是json方式,当中直接传参是无效的,可能是一个BUG,然而我一直踩到这个坑。使用这个插件,最好都用JSON格式吧。
player.loadPlaylist ({ listType:'playlist', list:'PLEL8booG6gbCZJwSUkvEWZYdUuzxuLHJo' });