isAudioPlaying

by Thornton_Fernbacher

HTML

<p>Probably only works in chrome (as of 3/2020)</p>
<p>Click start, then select this tab in "Chrome Tab" from the popup, check "Share Audio" and click "Share"</p>

<p>
  <button id="start">Start</button>
  <div id="check"></div>
</p>

<video width="200" controls>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>
<iframe width="200" src="https://www.youtube.com/embed/kLp_Hh6DKWc" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<audio controls src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3">
  Your browser does not support the
  <code>audio</code> element.
</audio>

<canvas id="oscilloscope"></canvas>

CSS

body {
  font-family:monospace;
}

#check::after {
  color: lightpink;
  content: "Audio not playing";
}

#check.playing::after {
  color: lightgreen;
  content: "Audio playing";
}

.ready #start {
  display: none;
}

#check {
  display: none;
}

.ready #check {
  display: block;
}

JavaScript

// based on examples from MDN docs
var startBtn = document.getElementById('start');
var checkBtn = document.getElementById('check');

var audioCtx = new(window.AudioContext || window.webkitAudioContext)();

var analyser = audioCtx.createAnalyser();

//as small as possible
analyser.fftSize = 32;
analyser.smoothingTimeConstant = 1;
//pick up very quiet sound
analyser.minDecibels = -200;
analyser.maxDecibels = -199;

var bufferLength = analyser.fftSize;
var dataArray = new Float32Array(bufferLength);

window.isAudioPlaying = () => {
  analyser.getFloatTimeDomainData(dataArray);
  for (var i = 0; i < bufferLength; i++) {
    if (dataArray[i] != 0) return true;

  }
  return false;
}


startBtn.onclick = function() {
  startBtn.onclick = null;

  navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: true,
      preferCurrentTab: true,
      selfBrowserSurface: "include"
    })
    .then(stream => {
      if (stream.getAudioTracks().length > 0) {
        var source = audioCtx.createMediaStreamSource(stream);
        source.connect(analyser);

        document.body.classList.add('ready');
      } else {
        console.log('Failed to get audiostream. Audio not shared or browser not supported')
      }


    }).catch(err => console.log("Unable to open capture: ", err));
    audioCtx.resume();
}

function checkAudio() {
  check.classList.toggle('playing', window.isAudioPlaying());
  window.requestAnimationFrame(checkAudio);
}

checkAudio();