Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

media player - Detect if audio is playing in browser Javascript

Is there a global way to detect when audio is playing or starts playing in the browser.

something like along the idea of if(window.mediaPlaying()){...

without having the code tied to a specific element?

EDIT: What's important here is to be able to detect ANY audio no matter where the audio comes from. Whether it comes from an iframe, a video, the Web Audio API, etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No one should use this but it works.

Basically the only way that I found to access the entire window's audio is using MediaDevices.getDisplayMedia().

From there a MediaStream can be fed into an AnyalizerNode that can be used to check the if the audio volume is greater than zero.

Only works in Chrome and maybe Edge (Only tested in Chrome 80 on Linux)

JSFiddle with <video>, <audio> and YouTube!

Important bits of code (cannot post in a working snippet because of the Feature Policies on the snippet iframe):

var audioCtx = new AudioContext();
var analyser = audioCtx.createAnalyser();

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;
}

navigator.mediaDevices.getDisplayMedia({
     video: true,
     audio: true
   })
   .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 stream. Audio not shared or browser not supported');
      }

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...