gpt4 book ai didi

javascript - 从 iframe 标签获取嵌入的 youtube 播放列表视频的当前时间戳

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

我在我的网站上嵌入了一个 youtube 视频(这是一个播放列表链接),我想在用户播放视频时获取视频的时间戳。 youtube 视频嵌入在我的网站上:

<iframe src="//www.youtube.com/embed/eykoKxsYtow?list=PLeo1K3hjS3usILfyvQlvUBokXkHPSve6S" width="560" height="314" allowfullscreen="allowfullscreen"></iframe>

现在当这个视频正在播放时,我想获取视频的当前时间戳。我想将其存储在我的数据库中,以便下次用户登录我的网站时可以开始播放视频。如何使用 Javascript 执行此操作?

这是我尝试过的。
ytplayer = document.getElementsByTagName("iframe")[0];
ytplayer.getCurrentTime();

抛出错误:
VM1406:1 Uncaught TypeError: ytplayer.getCurrentTime is not a function
at <anonymous>:1:10

获得时间戳后,现在我还想将视频设置为该时间戳,用户再次登录。如何使用 Javascript 设置视频位置?

我需要完整的工作代码,youtube API 有点难以理解。

最佳答案

你可以试试这个,它完美地工作。

把它放到你的 html 文件中。

<div id="player"></div>

现在从 iframe 获取视频链接标签
let url = document.getElementsByTagName('iframe')[0].src;

从链接中获取视频的 id
function youtube_parser(url){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
return (match&&match[7].length==11)? match[7] : false;
}
let video_id = youtube_parser(url);

一旦您收到 video_id ,现在您可以开始了。
<script>
// This code loads the IFrame Player API code asynchronously.
let tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
let firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


// This function creates an <iframe> (and YouTube player) after the API code downloads.
// player is a global variable
let player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: video_id,
events: {
'onReady': onPlayerReady,
}
});
}
</script>

现在您可以使用 player 进行 ajax 调用变量,这个变量类似于你的 javascript video player element ,您可以使用它处理所有与视频相关的事件。
function onPlayerReady(event) {
$.ajax({
//make ajax call to get the timestamp of the video fro the database, if the user has watched this video.
event.target.playVideo();
});
}

let interval = setInterval(function(){
$.ajax({
// Make AJAX call to store the timestamp of video already watched at regular time intervals
});
}, time_interval);

关于javascript - 从 iframe 标签获取嵌入的 youtube 播放列表视频的当前时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58870093/

25 4 0
文章推荐: python - 尝试使用 pandas datareader 获取股票数据时出现 SSL 错误
文章推荐: php - LAST_INSERT_ID 更可靠的解决方案
文章推荐: python - 将 django 变量添加到