Created
March 2, 2020 17:04
-
-
Save robwalch/6324bd94dddb49bfd4696745796b9002 to your computer and use it in GitHub Desktop.
Detect audio playback in video element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use WebAudio API to detect audio playback with volume | |
// Returns early with false when audio could not be playing | |
// Returns null if WebAudio API cannot be used while media is in a playing state | |
function isMediaPlayingAudio(mediaElement) { | |
if (media.paused || media.muted || media.volume === 0 || media.played.length < 1) { | |
return false; | |
} | |
let analyser = media.audioAnalyser; | |
let audioCtx = media.audioCtx; | |
if (!analyser) { | |
if (!window.AudioContext) { | |
return null; | |
} | |
try { | |
audioCtx = new window.AudioContext(); | |
const source = audioCtx.createMediaElementSource(media); | |
analyser = audioCtx.createAnalyser(); | |
analyser.fftSize = 256; | |
source.connect(analyser).connect(audioCtx.destination); | |
media.audioAnalyser = analyser; | |
media.audioCtx = audioCtx; | |
} catch (error) { | |
console.warn('Could not analyze audio', error); | |
return null; | |
} | |
} | |
const data = new Uint8Array(analyser.frequencyBinCount); | |
analyser.getByteTimeDomainData(data); | |
return data.some(int => int !== 128); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment