YouTube IFrame APIを使って動画を埋め込むメモ

サイトの背景にYouTubeにアップロードした動画を流したいとかいう要望に出くわしたのでメモ。

公式ドキュメントはここ
参考 : iframe 組み込みの YouTube Player API リファレンス

使い方

いちばん簡単なやつ。
htmlファイルの<body>〜</body>内の動画を表示させたい部分に、以下のhtmlを記述。

<div id="sample"></div>

次に、</body>の直前に以下を記述

<script src="./sample.js"></script>

jsファイルの中身。

まず、APIを読み込む記述。公式ドキュメントにあるとおり。

// IFrame Player API の読み込み
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

その下に、YouTubeを表示させる記述。

// YouTubeの埋め込み
var player;
function onYouTubePlayerAPIReady() {
 player = new YT.Player('sample', {
  width: '100%',
  height: '1000',
  videoId: '8hL4jlYj78U'
 });
}

横幅と高さのサイズ指定は、単位を省略するとpxとして解釈される。videoIdの代わりにPlaylistのパラメータにすることもできる。
パラメータ(playerVars{}で指定してる部分)とかいろいろ追加して、実際にはこんな感じ。

// YouTubeの埋め込み
var player;
function onYouTubePlayerAPIReady() {
 player = new YT.Player('sample', {
  width: '100%',
  height: '1000',
  videoId: '8hL4jlYj78U',
  playerVars: {
   autoplay: 1,
   controls: 0,
   loop: 1,
   modestbranding: 1,
   showinfo: 0,
   wmode: 'transparent'
  }
 });
}

最終的に実装したのが以下の形。
動画を幾つか放り込んだプレイリストを連続再生した。音声はミュート。
ブラウザサイズに合わせて全画面で表示するように設定。
参考 : YouTubeの動画を背景に利用する(YouTube IFrame API)

// IFrame Player API の読み込み
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// YouTubeの埋め込み
var player;
function onYouTubePlayerAPIReady() {
 player = new YT.Player('sample', {
  playerVars: {
   listType: 'playlist',
   list: 'PL-xxxxxxx', // プレイリストのID
   controls: 0,
   autoplay: 1,
   loop: 1,
   modestbranding: 1,
   showinfo: 0,
   wmode: 'transparent'
  },
  events: {
   onReady: onPlayerReady
   //onStateChange: onPlayerStateChange
  }
 });
}

function onPlayerReady(event) {
 //event.target.playVideo();
 event.target.mute(); // 音声ミュート
}

// ブラウザサイズにあわせて全画面表示
function resizeMovie () {
var $w = $(window),
bw = 1200, //基準にする横幅
bh = (bw/16) * 9, //基準にする高さ(16:9)
w = $w.width(), //表示サイズ(幅)
h = $w.height(), //表示サイズ(高さ)
mw = w, //動画サイズ(幅)
mh = Math.round(bh * (mw/bw)); //動画サイズ(高さ)

if ( mh < h ) { //動画の高さが表示サイズの高さより小さかったら
 mh = h;
 mw = Math.round(bw * (mh/bh));
}

$('#sample').css({
 width: mw,
 height: mh,
 marginTop: (h - mh)/2,
 marginLeft: (w - mw)/2
});

}

resizeMovie();

$(window).resize(resizeMovie);

参考 : YouTube 埋め込みプレーヤーとプレーヤーのパラメータ