Use javascript to detect if an MP4 video has a sound track

谁说我不能喝 提交于 2021-02-07 02:46:18

问题


I am creating a custom controller for MP4 video on a web page. The controller includes a volume slider. Some of the videos that are to be played have no sound track. It would be good to disable the volume slider for these videos, so that the user is not confused when changing the position of the volume slider has no effect.

Is there a property or a trick for checking if an MP4 file has an audio track? (jQuery is an option).

Edit: using @dandavis's suggestion, I now have this solution for Chrome (and .ogg on 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 video.webkitAudioDecodedByteCount value is initially 0. In my tests, it may take up to 256ms to get populated with a non-zero value, so I have included a timeout to keep checking (for a while).


回答1:


There might be a better way of doing this, although it's fairly simple just using regular javascript for webkit or mozilla enabled browsers. webkit utilizes 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's also a function this.webkitAudioDecodedByteCount, however, I've never had any luck making it work.



来源:https://stackoverflow.com/questions/30604696/use-javascript-to-detect-if-an-mp4-video-has-a-sound-track

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!