Skip to content Skip to sidebar Skip to footer

How To Listen Volume Changes Of Youtube Iframe?

Here I found an example how I can listen Play\Pause button of youtube iframe. player.addEventListener('onStateChange', function(e) { console.log('State is:', e.data); }); Now

Solution 1:

I inspected the code of YouTube Player Demo page and found that the html line which shows the current YouTube volume (<span id="volume">**</span>) constantly blinking (~ 2 times per 1 sec), so I can assume this demo page uses something like this:

// YouTube returns Promise, but we need actual data
self = thissetInterval(function () { self.player.getVolume().then(data => { self.volumeLv = data }) }, 250)

Possibly not the best method, but it seems there is no other option (I also tried to listen changes in the appropriate style of the volume bar, but no luck due to the cross-origin problem).

So, this let us 'listen' volume changes of youtube.

Just in case, if someone wants to set youtube volume, you need to use [this.]player.setVolume(volume_from_0_to_100)

Solution 2:

See this question.

You can listen to postMessage events emitted by the IFrame and react only to the volume change ones:

// Instantiate the Player.functiononYouTubeIframeAPIReady() {
  var player = newYT.Player("player", {
    height: "390",
    width: "640",
    videoId: "dQw4w9WgXcQ"
  });

  // This is the source "window" that will emit the events.var iframeWindow = player.getIframe().contentWindow;

  // Listen to events triggered by postMessage.window.addEventListener("message", function(event) {
    // Check that the event was sent from the YouTube IFrame.if (event.source === iframeWindow) {
      var data = JSON.parse(event.data);

      // The "infoDelivery" event is used by YT to transmit any// kind of information change in the player,// such as the current time or a volume change.if (
        data.event === "infoDelivery" &&
        data.info &&
        data.info.volume
      ) {
        console.log(data.info.volume); // there's also data.info.muted (a boolean)
      }
    }
  });
}

See it live.

Note that this relies on a private API that may change at anytime without previous notice.

Post a Comment for "How To Listen Volume Changes Of Youtube Iframe?"