前言:
紀錄一下這次開發 Youtube Iframe API 實作遇到一些小問題
參考資料:
Youtube Iframe API 常用功能
YouTube JavaScript API not triggering onYouTubeIframeAPIReady
需求
- 影片自動播放,並能從外部控制聲音開啟或靜音(示意圖如下)
實作遇到問題點
- youtubeIframe API 全域只能載入一次
- 靜音時無法自動播放
解決方法
- 先建立
onYouTubeIframeAPIReady
function
- 當影片載入後,在 onReady 方法中呼叫
onPlayerReady
- 將影片先關靜音才能自動播放
- 如果需要多個
onYouTubeIframeAPIReady
則必須自己先建立一個實體,才能各別控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| var player; function onYouTubeIframeAPIReady() { player = new YT.Player("video0", { events: { onReady: onPlayerReady, }, }); } function onPlayerReady(e) { checkYT(); e.target.mute().playVideo(); const toggleVoice = document.querySelector(".toggleVoice"); toggleVoice.addEventListener("click", () => { if (e.target.isMuted()) { toggleVoice.src = "./content/assets/img/voice.svg"; e.target.unMute().playVideo(); } else { toggleVoice.src = "./content/assets/img/novoice.svg"; e.target.mute().playVideo(); } }); }
var player2; function yt_init() { player2 = new YT.Player("video1", { events: { onReady: onPlayerReady1, }, }); }
var checkYT = () => { if (YT && YT.loaded) { yt_init() } };
function onPlayerReady1(e) { e.target.mute().playVideo(); const toggleVoice1 = document.querySelector(".toggleVoice1"); toggleVoice1.addEventListener("click", () => { if (e.target.isMuted()) { toggleVoice1.src = "./content/assets/img/voice.svg"; e.target.unMute().playVideo(); } else { toggleVoice1.src = "./content/assets/img/novoice.svg"; e.target.mute().playVideo(); } }); }
|
- 必須要注意
iframe
連結必須加上 enablejsapi 參數 且 allow
屬性 也必須帶上 autoplay
1 2 3 4 5 6 7 8
| <iframe src="https://www.youtube.com/embed/OBH26hA6GLA?enablejsapi=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen id="video0" ></iframe>
|