Detect if audio is playing in browser Javascript

前端 未结 5 1145
萌比男神i
萌比男神i 2020-12-31 04:49

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()){...

5条回答
  •  抹茶落季
    2020-12-31 05:09

    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.

提交回复
热议问题