Skip to content

Instantly share code, notes, and snippets.

@robwalch
Created March 2, 2020 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robwalch/6324bd94dddb49bfd4696745796b9002 to your computer and use it in GitHub Desktop.
Save robwalch/6324bd94dddb49bfd4696745796b9002 to your computer and use it in GitHub Desktop.
Detect audio playback in video element
// 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