Use javascript to determine if an MP4 video has an audio track.

I am creating a custom controller for MP4 video on a web page. The controller includes a volume slider. Some of the videos that you want to play do not have an audio track. It would be nice to turn off the volume slider for these videos so that the user does not get confused when changing the position of the volume slider has no effect.

Is there a feature or trick to check for the presence of an audio track in an MP4 file? (jQuery is an option).

Edit: using the @dandavis suggestion, I now have this solution for Chrome (and .ogg for Opera):

var video = document.getElementById("video") var volume = document.getElementById("volume-slider") function initializeVolume() { var enableVolume = true var delay = 1 if (video.webkitAudioDecodedByteCount !== undefined) { // On Chrome, we can check if there is audio. Disable the volume // control by default, and reenable it as soon as a non-zero value // for webkitAudioDecodedByteCount is detected. enableVolume = false startTimeout() function startTimeout () { if (!!video.webkitAudioDecodedByteCount) { enableVolume = true toggleVolumeEnabled(enableVolume) } else { // Keep trying for 2 seconds if (delay < 2048) { setTimeout(startTimeout, delay) delay = delay * 2 } } } } toggleVolumeEnabled(enableVolume) } function toggleVolumeEnabled(enableVolume) { volume.disabled = !enableVolume } 

The value of video.webkitAudioDecodedByteCount is initially 0. In my tests, it may take up to 256 ms to fill in a non-zero value, so I turned on the timeout to continue checking (for a while).

+6
source share
1 answer

Maybe the best way to do this is, although it's pretty simple to use regular javascript for webkit or mozilla browsers. webkit uses this.audioTracks and mozilla uses this.mozHasAudio respectively:

 document.getElementById("video").addEventListener("loadeddata", function() { if ('WebkitAppearance' in document.documentElement.style) var hasAudioTrack = this.audioTracks.length; else if (this.mozHasAudio) var hasAudioTrack = 1; if (hasAudioTrack > 0) alert("audio track detected"); else alert("audio track not detected"); }); 
 <video id="video" width="320" height="240" controls> <source src="http://media.w3.org/2010/05/video/movie_300.mp4" type="video/mp4"> </video> 

There is also a function this.webkitAudioDecodedByteCount , but I never managed to get it to work.

0
source

Source: https://habr.com/ru/post/988407/


All Articles