2013/09/09

[js] Youtubeプレイヤーのクリックイベント登録

あるミュージシャンのサイトでsoundManagerを使って音楽を再生できるようにした。
ページによってはYouTubeが貼られてあるページがあって、YouTubeを再生する時にはBGMは停止することになった。

iPadやらも対象になっているのでYouTubeはiframeで埋め込んでる。
当然iframe内はYouTubeのドメインになっているので、JavaScriptで中を覗くことも、プレイヤーにクリックイベントを登録することもできない。
  1. do ->  
  2.  # iframeがひとつしかない状態でしか確認してないので、複数ある場合は要注意  
  3.  $iframes = $('iframe')  
  4.  $ytFrames = $iframes.filter ->  
  5.   # facebookのiframeなどもあるのでsrcをチェック  
  6.   if this.src.indexOf 'youtube.com' != -1  
  7.    srcParts = this.src.split '/'  
  8.    id = srcParts.pop().split('?')[0]  
  9.    # YoutubeのAPIで使用するので、動画IDを保存しておく  
  10.    this.setAttribute 'data-movieid', id  
  11.    # iframeを作り変えるので、その格納用divを作成&挿入  
  12.    $(this).after '<div id="ytframe-' + id + '"></div>'  
  13.    return true  
  14.  
  15.  # youtubeのiframeがなければやめる  
  16.  if $ytFrames.size() == 0  
  17.   return  
  18.  
  19.  # 後々取得しやすいyにクラス名追加  
  20.  $ytFrames.addClass 'js-yt-frame'  
  21.  
  22.  # ここはドキュメントに書いてあった。iframeのAPIを使用するために必要なscriptを読み込む  
  23.  tag = d.createElement 'script'  
  24.  tag.src = 'https://www.youtube.com/iframe_api'  
  25.  $('head').append tag  
  26.  
  27. # scriptが読み込まれると、この名前の関数が呼ばれる  
  28. @onYouTubeIframeAPIReady = ->  
  29.  # 判別用につけたクラス名で取得  
  30.  $ytFrames = $('.js-yt-frame')  
  31.  $ytFrames.each ->  
  32.   $this = $(this)  
  33.   # 既存のiframeを新しく作るものと置き換えるので一旦非表示  
  34.   $this.hide()  
  35.   frame = this  
  36.   movieId = frame.getAttribute 'data-movieid'  
  37.   # APIにあるオブジェクトをnew。これでiframeが作られる  
  38.   player = new YT.Player 'ytframe-' + movieId,  
  39.    # 幅・高さともに200px以上ないと再生できないので、最低値を設定  
  40.    width: Math.max(frame.getAttribute('width'), 200)  
  41.    height: Math.max(frame.getAttribute('height'), 200)  
  42.    videoId: movieId  
  43.    events:  
  44.     onReady: (e)->  
  45.      # もともとあったiframeを削除  
  46.      $this.remove()  
  47.     onStateChange: (e)->  
  48.      # クリックイベント登録  
  49.      if e.data == YT.PlayerState.PLAYING  
  50.       # 動画が再生状態になった場合の処理  
  51.       # 今回はここでsoundManagerを止めた。  
  52.  
  53.      # もちろん停止状態になったら…とかも可能  
参考サイト: YouTube Player API Reference for iframe Embeds(英語)

0 件のコメント:

コメントを投稿