Advertisement
limontec

Autoplay and mute Youtube video

Aug 6th, 2015
7,135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <div id="player"><iframe width="300" height="200" src="https://www.youtube.com/embed/url-id-video" frameborder="0" allowfullscreen></iframe></div>
  2.  
  3.     <script>
  4.       // 2. This code loads the IFrame Player API code asynchronously.
  5.       var tag = document.createElement('script');
  6.  
  7.       tag.src = "https://www.youtube.com/iframe_api";
  8.       var firstScriptTag = document.getElementsByTagName('script')[0];
  9.       firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  10.  
  11.       // 3. This function creates an <iframe> (and YouTube player)
  12.       //    after the API code downloads.
  13.       var player;
  14.       function onYouTubeIframeAPIReady() {
  15.         player = new YT.Player('player', {
  16.           height: '200',
  17.           width: '300',
  18.           videoId: 'url-id-video',
  19.           events: {
  20.             'onReady': onPlayerReady,
  21.             'onStateChange': onPlayerStateChange
  22.           }
  23.         });
  24.       }
  25.  
  26.       // 4. The API will call this function when the video player is ready.
  27.       // In "event.target.setVolume (0)" is with audio on mute (value: 0).
  28.       // To put maximum volume change to "event.target.setVolume (100)"
  29.       function onPlayerReady(event) {
  30.         event.target.playVideo();
  31.         event.target.setVolume(0);
  32.       }
  33.  
  34.       // 5. The API calls this function when the player's state changes.
  35.       //    The function indicates that when playing a video (state=1),
  36.       //    the player should play for two minutes and then stop.
  37.       //    To increase or decrease the time just change the value 120000, which is equivalent to two minutes.
  38.       //    Code edited by limontec.com
  39.       var done = false;
  40.       function onPlayerStateChange(event) {
  41.         if (event.data == YT.PlayerState.PLAYING && !done) {
  42.           setTimeout(stopVideo, 120000);
  43.           done = true;
  44.         }
  45.       }
  46.       function stopVideo() {
  47.         player.stopVideo();
  48.       }
  49.     </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement