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.

Asked By: Chris
||

Answer #1:

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));
Answered By: Trobol

Answer #2:

Verily, I search a lot and read all MDN docs about Web Audio API but don't find any global flag on window that shows audio playing but I have a tricky way that shows ANY audio playing, no matter an iframe or video but about Web Audio API I'm not sure, the tricky way is:

const allAudio = Array.from( document.querySelectorAll('audio') );
const allVideo = Array.from( document.querySelectorAll('video') );
const isPlaying = [...allAudio, ...allVideo].some(item => !item.paused);

Now, buy the isPlaying flag we can detect playing in the browser.

Answered By: AmerllicA

Answer #3:

I was looking for a solution in Google, but i didn't find anything yet. Maybe you could check some data that has X value only when audio is playing. If you have some button that start playing the audio file, maybe you can be sure that the audio is playing by adding some event listener on the rep. button...

Maybe something like adding an event listener to the "audio" tag? If i remember correctly, audio tag has a "paused" attribute... And now i just remember that the audio has "paused" attribute...

Also, you may want to check this topic HTML5 check if audio is playing?

i jus find it five seconds ago jaja

Answered By: Emilio

Answer #4:

There is a playbackState property (https://developer.mozilla.org/en-US/docs/Web/API/MediaSession/playbackState), but not all browsers support it.

if(navigator.mediaSession.playbackState === "playing"){...
Answered By: NinaW

Answer #5:

What about adding an event to all of the audio players on a page? (untested)

function AudioIsPlaying() {
    console.log('Audio is playing');

    // your code here
}

let audioElements = document.getElementsByTagName('audio');
for (let i = 0; i < audioElements.length; i++) {
    audioElements[i].onplaying = (element) => {
        AudioIsPlaying();
    }
}

onplaying spec: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playing_event

Answered By: Ed Lucas
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles