HTML5视频,如何在没有音轨时检测?

Lou*_*lor 11 javascript html5

我正在制作一个Chrome应用程序,我想为视频播放提供自定义控件,但我在使用静音按钮时遇到了一些困难.将在应用程序中播放的大多数视频都是静音的,因此我希望能够在没有音频轨道的情况下禁用按钮,就像Chrome使用默认控件一样.

尝试使用音量值,但即使没有音轨,它也会返回"1".检查视频是否静音也不起作用.

这是一个片段.

有什么建议?

fre*_*nte 11

更短的功能基于upuoth的答案,并扩展到支持IE10 +

function hasAudio (video) {
    return video.mozHasAudio ||
    Boolean(video.webkitAudioDecodedByteCount) ||
    Boolean(video.audioTracks && video.audioTracks.length);
}
Run Code Online (Sandbox Code Playgroud)

用法:

var video = document.querySelector('video');
if(hasAudio(video)) {
    console.log("video has audio");
} else{
    console.log("video doesn't have audio");
}
Run Code Online (Sandbox Code Playgroud)

  • 大家不要忘记视频元素上的 `addEventListener("loadeddata")`。 (3认同)

小智 9

在某些时候,浏览器可能会开始实现audioTracks属性.目前,您可以使用webkitAudioDecodedByteCountwebkit和mozHasAudiofirefox.

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");
});
Run Code Online (Sandbox Code Playgroud)