gpt4 book ai didi

javascript - 具有自定义开始和结束时间的自定义 YouTube 播放列表

转载 作者:行者123 更新时间:2023-12-01 01:20:26 25 4
gpt4 key购买 nike

我正在尝试根据示例 here 制作自定义 YouTube 播放列表。

但是,YouTube 播放器会“卡住”并跳过视频(在我的例子中,中间的视频被跳过)。该代码应该迭代下面的数组并一次播放一个视频,每个视频都有单独的开始/结束时间。

如何才能使这项工作正常进行。 (注意,下面的代码需要上传到网站才能工作。显然从本地计算机上,它不起作用)这是我正在使用的代码:

<html>
<body>

<div id="ytplayer"></div>


<script>// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var i = 0;
var videoId_arr = ['O57DyNMRGY8','-Yh2QGJBd2U','M7lc1UVf-VE'];
var startSeconds_arr = [41,26,17];
var endSeconds_arr = [50,40,30];

// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;

var playerConfig = {
height: '360',
width: '640',
videoId: videoId_arr[i],
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 1, // Show pause/play buttons in player
showinfo: 1, // Hide the video title
modestbranding: 0, // Hide the Youtube Logo
fs: 1, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 3, // Hide the Video Annotations
start: startSeconds_arr[i],
end: endSeconds_arr[i],
autohide: 0, // Hide video controls when playing
},
events: {
'onStateChange': onStateChange
}
};


function onYouTubePlayerAPIReady() {

player = new YT.Player('ytplayer', playerConfig);
}

function onStateChange(state) {
if (state.data === YT.PlayerState.ENDED) {
i++;
if(typeof videoId_arr[i] === 'undefined')
return;

player.loadVideoById({
videoId: videoId_arr[i],
startSeconds: startSeconds_arr[i],
endSeconds: endSeconds_arr[i]
});
}
}

</script>
</body>
</html>

最佳答案

我已经测试了您的代码,我发现状态由于某些未知原因正在快速变化。尽管视频未播放,状态有时的值 0 等于 YT.PlayerState.ENDED

您可以通过 onStateChange 函数中的控制台记录 state.data 来查看它。

一个小改动解决了这个问题:

function onStateChange(state) {
var _video_url = state.target.getVideoUrl();
var _video_id = _url.split('v=')[1];
var _current_index = videoId_arr.indexOf(_video_id) +1;

console.log('State: ', _video_id, _current_index, state );

// ensure that the video has been played
if (state.data === YT.PlayerState.ENDED && player.getCurrentTime() >= endSeconds_arr[i]) {
i++;
if(typeof videoId_arr[i] === 'undefined'){
i = 0; // rest the counter
return;
}
}
}

为了使代码正常运行,您应该禁用 Video Resumer 或类似的浏览器插件 - 因为它们可以更改 YouTube 视频的状态或从您上次停止的位置恢复视频

fiddle :https://jsfiddle.net/_kdts/Lx91ehdw/

关于javascript - 具有自定义开始和结束时间的自定义 YouTube 播放列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54285240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com