javascriptyoutube-api

How to play youTube video sound called through Javascript API


Video are not playing sound when calling using Youtube API. how we can play sound of a youTube video when played/run. Is there any other API or any parameter we can user. I have below YouTube API call and HTML and its working fine but not getting sound because I have number YouTube video with sound in website.

// 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() {
      // This function seems to be needed, so, don't remove it from your code.
     }

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

    // Render the IFRAME once the button is clicked.
    function youtubevideo(elem, videoIdval) {
const playerElem = elem.parentNode.getElementsByTagName('div')[0];


    // "Destroy" the "player" > for allow re-create it with the new "clicked" video_id.
    //if (player != null || player != undefined) {
     // player.destroy();
    //}

    // Build the iframe with the "clicked" video_id: 
    player = new YT.Player(playerElem, {
      width: '280px',
      height: '163px',
      videoId: videoIdval,
      playerVars: {
        'autoplay': 1,
        'playsinline': 1,
        'origin': window.location.href
      },
      events: {
        'onReady': onPlayerReady
      }
     });
   elem.style.display="none";
     }
 <div>
           <div id="player1"></div>
           <button onclick="youtubevideo(this, 'o5x6t68xVVE')">Click me</button>
           </div>   

           <div>
           <div id="player2"></div>
          <button onclick="youtubevideo(this, 'wJp-BZpVBPA')">Click me</button>
           </div>
           <div>
           <div id="player3"></div>
          <button onclick="youtubevideo(this, 'sPhhZg9v9NU')">Click me</button>
           </div>


Solution

  • Try removing event.target.mute(); line 17 i think inside the onPlayerReady function