2017-05-26 129 views
0

搜索並找到許多類似問題後,我無法找到正確的答案。所以我正在使用YouTube Iframe API,並且我知道自動播放等不適用於手機。我創建了一個元素,顯示在手機上,所以當用戶點擊該按鈕時,它應該播放視頻。但我只收到此消息:「如果播放不立即開始,請嘗試重新啓動設備」YouTube Iframe API - 在手機上播放視頻

var playElement = document.createElement("div"); 
playElement.style.display = "none"; 

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { 
    playElement.style.display = "block"; 
} 

var player; 
function onYouTubeIframeAPIReady() { 
    player = new YT.Player(child, { 
     width: '100%', 
     height: '100%', 
     videoId: youtubeID, 
     playerVars: { 
     'iv_load_policy': 3, 
     'enablejsapi': 1, 
     'disablekb': 1, 
     'autoplay': 1, 
     'loop': 0, 
     'controls': 0, 
     'showinfo': 0, 
     'rel': 0, 
     'mode': 'transparent' 
     }, 
     events: { 
     'onReady': onPlayerReady, 
     'onStateChange': onPlayerStateChange 
     } 
    }); 
} 

playElement.onclick = function() { 
    player.playVideo();; 
}; 

任何確實有實際工作解決方案的人?

回答

0

記住玩家是指ID爲'player'的div。您可以從youtube api doc上的示例代碼開始。它會在視頻加載時自動播放。您也可以添加您的playerVar選項。

手機視頻自動播放的注意事項。您可以自動播放,但必須靜音。因此,您可以在加載時嘗試添加player.mute(),並設置一個點擊處理程序以便再次取消抑制,如果這是您更喜歡的。

<!DOCTYPE html> 
 
<html> 
 
    <body> 
 
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. --> 
 
    <div id="player"></div> 
 

 
    <script> 
 
     // 2. This code loads the IFrame Player API code asynchronously. 
 
     var tag = document.createElement('script'); 
 

 
     tag.src = "https://www.youtube.com/iframe_api"; 
 
     var firstScriptTag = document.getElementsByTagName('script')[0]; 
 
     firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 
 

 
     // 3. This function creates an <iframe> (and YouTube player) 
 
     // after the API code downloads. 
 
     var player; 
 
     function onYouTubeIframeAPIReady() { 
 
     player = new YT.Player('player', { 
 
      height: '390', 
 
      width: '640', 
 
      videoId: 'M7lc1UVf-VE', 
 
      events: { 
 
      'onReady': onPlayerReady, 
 
      'onStateChange': onPlayerStateChange 
 
      }, 
 
      playerVars 
 
     }); 
 
     } 
 

 
     // 4. The API will call this function when the video player is ready. 
 
     function onPlayerReady(event) { 
 
     event.target.playVideo(); 
 
     } 
 

 
     // 5. The API calls this function when the player's state changes. 
 
     // The function indicates that when playing a video (state=1), 
 
     // the player should play for six seconds and then stop. 
 
     var done = false; 
 
     function onPlayerStateChange(event) { 
 
     if (event.data == YT.PlayerState.PLAYING && !done) { 
 
      setTimeout(stopVideo, 6000); 
 
      done = true; 
 
     } 
 
     } 
 
     function stopVideo() { 
 
     player.stopVideo(); 
 
     } 
 
    </script> 
 
    </body> 
 
</html>

相關問題