如何为YouTube API传递变量ID



我是CS的新手,目前从事个人项目。我正在创建一个网络应用程序,用户可以将YouTube URL复制并粘贴到搜索框中的视频中,然后点击观看后就可以在同一网页上观看视频。为了获得视频ID,我使用了一个正则表达式:

function getId(url) {
const regExp = /^.*(youtu.be/|v/|u/w/|embed/|watch?v=|&v=)([^#&?]*).*/;
const match = url.match(regExp);
return (match && match[2].length === 11)
? match[2]
: null;
}

这就是我获得用户输入的方式:

var inputVal = document.getElementById("userInput").value;

为了获得视频ID,我在inputVal上从用户处调用getId

var newVideoId = getId(inputVal)

下面是用于在我的页面上播放视频的YouTube API。但是,我发现很难将newVideoId变量传递到player对象下的API。

// 2. This code loads the IFrame Player API code asynchronously.
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('player', {
height: '390',
width: '640',
videoId: 'newVideoId', //the problem lies here
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();
}
}

问题是,点击按钮后,我的屏幕上什么都没有显示。我能够console.logID;这意味着我从正则表达式中得到了正确的ID。

我将感谢任何关于如何在API中使用从用户那里获得的动态ID的帮助!感谢

要使用提供视频Id的iframe api播放视频,可以使用以下函数:

loadVideoById({'videoId': 'bHQqvYy5KYo',
'startSeconds': 5,
'endSeconds': 60,
'suggestedQuality': 'large'});

来自IFrame Player API:

此函数加载并播放指定的视频。

所需的videoId参数指定要播放的视频。在YouTube数据API中,视频资源的id属性指定ID。可选的startSeconds参数接受浮点/整数。如果已指定,则视频将从距离指定时间最近的关键帧。可选endSeconds参数接受浮点/整数。如果已指定,则视频将在指定时间停止播放。

这样就可以了。

最新更新