IFrame APIを使用して、動画の情報の取得するサンプル。
再生中の動画の長さ:0
動画のURL:
動画の埋め込みコード:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>設置サンプル:YouTube IFrame API:動画情報の取得</title>
<link rel="stylesheet" type="text/css" href="/content/lib/global.css" />
<style>
#playerbox { width:640px; height:390px; margin-bottom:10px; }
#controls { width:640px; text-align:center; }
#controls a { display:inline-block; margin:0; padding:5px 10px; text-decoration:none; width:6em; color:#fff; background:#000; text-align:center; }
#controls a:hover { background:#333; }
#duration { color:red; }
#videoURL { width:630px; display:block; }
#videoEmbedCode { width:630px; height:4em; display:block; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(function(){
var player;
var videoID="XfkXW49bXfo";
/* IFrame Player APIのコードをロード */
function fGetScript(){
$.ajax({
url:"http://www.youtube.com/player_api/",
dataType:"script",
success:function(data){
//dbg("done");
},
error:function(xhr, status, thrown) {
dbg(xhr);
fGetScript();
}
});
}
fGetScript();
/* プレーヤーの準備完了時 */
window.onYouTubeIframeAPIReady=function() {
dbg("onYouTubeIframeAPIReady");
loadPlayer(videoID);
}
/* プレーヤー生成 */
function loadPlayer(videoID) {
dbg("loadPlayer("+videoID+")");
if(!player){
player = new YT.Player(
'player',{
width: '640', /* 動画プレーヤーの幅 */
height: '390', /* 動画プレーヤーの高さ */
videoId: videoID, /* YouTube動画ID */
events: { /* イベント */
"onReady": onPlayerReady, /* プレーヤの準備完了時 */
"onStateChange": onPlayerStateChange, /* 動画プレーヤーのステータス変更 */
},
playerVars: {
"rel":0, // 関連動画の有無(default:1)
"showinfo":0, // 動画情報表示(default:1)
"controls":1 // コントロール有無(default:1)
}
}
);
}else{
player.cueVideoById(videoID);
}
}
function onPlayerReady(event){
/* プレーヤの準備完了時 */
//player.playVideo(); /* 再生開始 */
$("#videoURL").val(player.getVideoUrl()); /* 動画のURLを取得 */
$("#videoEmbedCode").val(player.getVideoEmbedCode()); /* 動画の埋め込みコードを取得 */
}
function onPlayerStateChange(event) {
/* プレーヤーのステータスが変更される度に発生 */
dbg("PlayerState:"+event.data);
if(event.data==YT.PlayerState.PLAYING){
$("#duration").html(player.getDuration());
}
}
function dbg(str){
$("#debuglog").val(str+"\n"+$("#debuglog").val());
if(window.console && window.console.log){
console.log(str);
}
}
});
</script>
<link rel="stylesheet" type="text/css" href="/common/css/example.css"></head>
<body id='example3' class='example'><div class="ads" style="margin:32px auto;text-align:center;"></div><h1 class='h'><a href='/'>PHP & JavaScript Room</a> :: 設置サンプル</h1>
<h3 class='h'>実行結果</h3>
<div id="wrap">
<h1>設置サンプル</h1>
<h2>YouTube IFrame API:動画情報の取得</h2>
<p>IFrame APIを使用して、動画の情報の取得するサンプル。</p>
<div id="playerbox"><div id='player'><!-- 動画プレーヤーの埋め込み --></div></div>
<p>再生中の動画の長さ:<span id="duration">0</span></p>
<p>動画のURL:<input type="text" id="videoURL" readonly /></p>
<p>動画の埋め込みコード:<textarea id="videoEmbedCode" readonly></textarea></p>
</div>
</body>
</html>