how do i program the youtube embed player to unmute when clicked

前端 未结 3 1472
囚心锁ツ
囚心锁ツ 2021-01-19 14:18

How do I set the youtube embedded player to unmute upon clicking it. You can see the embedded player i\'m referring to at http://www.harvestarmy.org home page. It\'s the one

相关标签:
3条回答
  • 2021-01-19 14:21

    Thank you for that answer! I implemented it a little differently, adding it to the onYouTubeIframeAPIReady function.

    I also reversed the initialized value of the isUnMuted variable. Functionally it is the same, but makes more sense this way.

    var player;
    var isUnMuted = false;
    window.onYouTubeIframeAPIReady = function() {
        player = new YT.Player('youTube', {
            videoId: '[myVideoId]',
            playerVars: {
                'rel': 0,
            },
            events: {
                'onReady': function() {
                    player.mute();
                    player.playVideo();
                },
                'onStateChange': function () {
                    if (player.isMuted() && player.getPlayerState() == 2 && !isUnMuted) {
                        player.unMute();
                        player.playVideo();
                        isUnMuted = true;
                    }
                }
            }
        });
    }
    

    This mimics closely the behavior of embedded videos in a Facebook newsfeed.

    0 讨论(0)
  • 2021-01-19 14:22

    This works. But unfortunately the pause icon fades in when the video is clicked. Even the video continues to run it is not a clean solution. I fixed it by placing a <div> with exactly the same size above the actual video iframe and use its click() function to unmute the video.

    HTML:

      <div class="video-container">
        <div class="video-dummy">
        </div>
        <div id="player">
        </div>
      </div>
    

    CSS:

    .video-container {
      position: relative;
      width: 640px;
      height: 390px;
    }
    
    .video-dummy {
      width: 640px; 
      height: 390px;
      position: absolute;
    }
    

    Javascript:

    $('.video-dummy').click(function(){
      player.unMute();
    });
    

    This works out well for me.

    0 讨论(0)
  • 2021-01-19 14:27

    I don't think it is possible, because there is not such thing as a 'click' or 'activate' event. However, you may try adding an event handler to the "onStateChange" event and unmute and unpause your player. I haven't tried it, but give it a try and see if this works:

    var isUnMuted = true;
    
    player.addEventListener("onStateChange", function(event) {
         if( player.isMuted() && player.getPlayerState() == 2 && isUnMuted ) {
              player.unMute();
              player.playVideo(); // resume playback
              isUnMuted = false;  // you want to run this once only! 
         }
    });
    
    0 讨论(0)
提交回复
热议问题