gpt4 book ai didi

javascript - 如何让相同的视频能够自动播放,或者第二次自动播放 player.playVideo()

转载 作者:行者123 更新时间:2023-12-05 00:33:37 26 4
gpt4 key购买 nike

目前,同一视频只能自动播放 1 次。
复制:单击 1 个 svg 播放按钮,然后单击 X .
然后第二次单击相同的 svg 播放按钮。
您会发现视频不会自动播放。
这是如何在代码中修复的,以便同一视频可以第二次自动播放?
我要么使用 autoplay , 或 player.playVideo();让视频播放第二次。
我不确定它会如何工作。
https://jsfiddle.net/2h7dgfe5/

const videoPlayer = (function makeVideoPlayer() {
const players = [];

const tag = document.createElement("script");
tag.src = "https://www.youtube.com/player_api";
const firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function createStopHandler(player) {
const stopButtons = document.querySelectorAll(".exit");
stopButtons.forEach(function stopButtonHandler(buttons) {
buttons.addEventListener("click", function buttonClickHandler() {
player.stopVideo();
});
});
}

function onPlayerReady(event) {
const player = event.target;
player.setVolume(100);
createStopHandler(player);
}

function addPlayer(video, settings) {
const defaults = {
height: 360,
host: "https://www.youtube-nocookie.com",
videoId: video.dataset.id,
width: 640
};
defaults.events = {
onReady: onPlayerReady
};

const playerOptions = combinePlayerOptions(defaults, settings);
const player = new YT.Player(video, playerOptions);
players.push(player);
return player;
}

return {
addPlayer
};
}());

const managePlayer = (function makeManagePlayer() {
const defaults = {
playerVars: {
autoplay: 1,
controls: 1,
disablekb: 1,
enablejsapi: 1,
fs: 0,
iv_load_policy: 3
}
};

最佳答案

问题出在您第一次启动播放器的方式上。当播放器刚刚创建时,有一个 onPlayerReady被调用的函数。此函数不会在弹出窗口第二次打开时调用。
您需要保留对播放器的引用,并在打开弹出窗口时找到您想要的播放器并执行以下操作:

    player.playVideo();
我看到你把它们留在这里: const players = [];但是当您打开弹出窗口时您无权访问它,因此您无法真正调用 .playVideo() .
我会花一些时间来创建一个结构,该结构根据弹出窗口保存播放器的引用,因此它类似于:
const players = new Map();

// key can be anything you may use to relate:
// - HTML reference -> the element you click could be your key
// - string
// - other object
// - number
players.set(anyReasonableKey, playerInstance)

// then click handler would be something like this
function onPlayButtonClick(event) {
const key = event.target;
const p = players.get(key); // event target is the key, the play button.

// if there is no player
if(typeof player === "undefined"){
// the creation with autoplay option should handle fist start of video, because you need to wait for onPlayerReady event
makePlayer(key) // here you create it for the first time, and pass the key so you could do the following inside of the function:
// players.set(key, player)

} else {
p.playVideo(); // if player exists, just start playing video
}
}

playButton.addEventListener("click", onPlayButtonClick)

或者......更简单的方法(但不是首选)是每次用户打开弹出窗口时重新创建播放器,这样它总是会根据您的初始化配置自动播放。

关于javascript - 如何让相同的视频能够自动播放,或者第二次自动播放 player.playVideo(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69458567/

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