There is a video that has an audio track, yet the volume is not zero or muted, resulting in the video being silent. I am looking for a way to determine if a video is audible so that I can perform specific functions accordingly.
I came across a method to check if a video contains an audio track from @upuoth, which works on most browsers except IE10+. Additionally, @brefd.it's method works for IE10+ but I need guidance on how to implement his code.
@upuoth's script
document.getElementById("video").addEventListener("loadeddata", function() {
if (typeof this.webkitAudioDecodedByteCount !== "undefined") {
// non-zero if video has audio track
if (this.webkitAudioDecodedByteCount > 0)
console.log("video has audio");
else
console.log("video doesn't have audio");
}
else if (typeof this.mozHasAudio !== "undefined") {
// true if video has audio track
if (this.mozHasAudio)
console.log("video has audio");
else
console.log("video doesn't have audio");
}
else
console.log("can't tell if video has audio");
});
@brefd's script
function hasAudio (video) {
return video.mozHasAudio ||
Boolean(video.webkitAudioDecodedByteCount) ||
Boolean(video.audioTracks && video.audioTracks.length);
}
var video = document.querySelector('video');
if(hasAudio(video)) {
console.log("video has audio");
} else{
console.log("video doesn't have audio");
}
I have set up three video clips: one with audible audio, one without any audio, and one that has an audio track but is not audible. The provided code only works for the first two clips and not the third one. To display an alert of "not audible" when playing the third clip, you can use the code from this JSFiddle link.