我尝试在我的rails应用中实现的功能是用户可以控制嵌入的YouTube视频。我正在使用youtube播放器api(指南:https://developers.google.com/youtube/iframe_api_reference)。
在指南中,它总是创建一个新的YT播放器:
// 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: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
我的问题是如何使用外部“播放”按钮播放已嵌入的YouTube视频。
错误发生在player = new YT.Player
行。我不想制作新的播放器,只需控制已经嵌入的视频。
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('video', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event){
event.target.playVideo();
document.id("start").click(function () {
player.playVideo();
});
}
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
我的iframe:
<iframe title="YouTube video player" id="video" width="540" height="290" src="http://www.youtube.com/embed/#{ youtube_id }?rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
带有播放按钮的标题视图:
<div id="start">
<%= image_tag("playback_play.png") %>
</div>
(rails app)
如果您需要更多代码,请告诉我,谢谢您的帮助!
答案 0 :(得分:0)
不是您问题的直接答案,而是潜在的解决方案:
<div id="player"></div>
<div id="start" style="display: none;">
<%= image_tag("playback_play.png") %>
</div>
<script>
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '#{ youtube_id }', // not sure if you want that or <%= youtube_id %> in this case
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event){
//event.target.playVideo(); // commented out -- uncomment if you want autoplay
document.id("start").show();
}
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>