ページによってはYouTubeが貼られてあるページがあって、YouTubeを再生する時にはBGMは停止することになった。
iPadやらも対象になっているのでYouTubeはiframeで埋め込んでる。
当然iframe内はYouTubeのドメインになっているので、JavaScriptで中を覗くことも、プレイヤーにクリックイベントを登録することもできない。
do ->
# iframeがひとつしかない状態でしか確認してないので、複数ある場合は要注意
$iframes = $('iframe')
$ytFrames = $iframes.filter ->
# facebookのiframeなどもあるのでsrcをチェック
if this.src.indexOf 'youtube.com' != -1
srcParts = this.src.split '/'
id = srcParts.pop().split('?')[0]
# YoutubeのAPIで使用するので、動画IDを保存しておく
this.setAttribute 'data-movieid', id
# iframeを作り変えるので、その格納用divを作成&挿入
$(this).after ''
return true
# youtubeのiframeがなければやめる
if $ytFrames.size() == 0
return
# 後々取得しやすいyにクラス名追加
$ytFrames.addClass 'js-yt-frame'
# ここはドキュメントに書いてあった。iframeのAPIを使用するために必要なscriptを読み込む
tag = d.createElement 'script'
tag.src = 'https://www.youtube.com/iframe_api'
$('head').append tag
# scriptが読み込まれると、この名前の関数が呼ばれる
@onYouTubeIframeAPIReady = ->
# 判別用につけたクラス名で取得
$ytFrames = $('.js-yt-frame')
$ytFrames.each ->
$this = $(this)
# 既存のiframeを新しく作るものと置き換えるので一旦非表示
$this.hide()
frame = this
movieId = frame.getAttribute 'data-movieid'
# APIにあるオブジェクトをnew。これでiframeが作られる
player = new YT.Player 'ytframe-' + movieId,
# 幅・高さともに200px以上ないと再生できないので、最低値を設定
width: Math.max(frame.getAttribute('width'), 200)
height: Math.max(frame.getAttribute('height'), 200)
videoId: movieId
events:
onReady: (e)->
# もともとあったiframeを削除
$this.remove()
onStateChange: (e)->
# クリックイベント登録
if e.data == YT.PlayerState.PLAYING
# 動画が再生状態になった場合の処理
# 今回はここでsoundManagerを止めた。
# もちろん停止状態になったら…とかも可能
参考サイト: YouTube Player API Reference for iframe Embeds(英語)
0 件のコメント:
コメントを投稿