javascript Youtube Javascript播放器ASPI“ytplayer不是一个功能”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26656836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Youtube Javascript player ASPI "ytplayer is not a function"
提问by em.rexhepi
I have this code in html:
我在 html 中有这个代码:
<div class="flex-video widescreen youtube">
<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/{{Video.v_id}}?autoplay=1&enablejsapi=1&autohide=1" frameborder="0" allowfullscreen> </iframe>
</div>
and this code in Javascript:
和这段 Javascript 代码:
function onYouTubePlayerReady(playerId) {
console.log("player ready");
ytplayer = document.getElementById("ytplayer");
}
When I type in Firefox console this:
当我在 Firefox 控制台中输入以下内容时:
ytplayer.playVideo();
I get the not function error:
我得到了 not 函数错误:
TypeError: ytplayer.playVideo is not a function
类型错误:ytplayer.playVideo 不是函数
Also the console.log("player ready");
does not print at all.
也console.log("player ready");
根本不打印。
Can anybody help me?
有谁能够帮我?
I want to controll the player with javascript api not with the IFrame api. And I want the video player to be in html5.
我想用 javascript api 而不是 IFrame api 来控制播放器。我希望视频播放器在 html5 中。
edit: I have the jspapi enabled (enablejsapi=1)
编辑:我启用了 jspapi (enablejsapi=1)
回答by vaskort
What works for me is adding the youtube by file and from the JS and then using the onYoutubePlayerAPIReady event like this:
对我有用的是通过文件和 JS 添加 youtube,然后使用 onYoutubePlayerAPIReady 事件,如下所示:
window.onYouTubePlayerAPIReady = function(){
var player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
回答by mpgn
If you follow the doc of the YouTube API Player
如果您遵循YouTube API 播放器的文档
HTML
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="player"></div>
</body>
</html>
JS
JS
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: 'l-gQLqv9f4o',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
}
}
function stopVideo() {
player.stopVideo();
}