HTML5 video, how to detect when there is no audio track?
Shorter function based on upuoth's answer and extended to support IE10+
function hasAudio (video) {
return video.mozHasAudio ||
Boolean(video.webkitAudioDecodedByteCount) ||
Boolean(video.audioTracks && video.audioTracks.length);
}
Usage:
var video = document.querySelector('video');
if(hasAudio(video)) {
console.log("video has audio");
} else{
console.log("video doesn't have audio");
}
At some point, browsers might start implementing the audioTracks property. For now, you can use webkitAudioDecodedByteCount
for webkit, and mozHasAudio
for firefox.
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");
});
For some reason @fregante's hasAudio
function stopped working in Chrome at some point - even after waiting for the "loadeddata" and "loadedmetadata" events, and even the "canplaythrough" event. It may have something to do with the video format I'm using (webm). In any case, I solved it by playing the video for a short amount of time:
// after waiting for the "canplaythrough" event:
hasAudio(video); // false
video.play();
await new Promise(r => setTimeout(r, 1000));
video.pause();
hasAudio(video); // true