简体   繁体   中英

Javascript conditions not working on audio check

So I've been staring at this problem for awhile. The following code looks at a video, and determines whether its actually playing sound, or is just silent. If it's silent, I want to loop it so it basically functions like a GIF.

The console logs the sound check accurately. I've been checking.

But the next bit of code (which applies the loop to the video) is run no matter what. It loops videos with sound, and I can't tell why.

 <script type="text/javascript">
document.getElementById("my-video_html5_api").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");
      var vid = document.getElementById("my-video_html5_api");
      vid.loop = true;
  }
  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");
      var vid = document.getElementById("my-video_html5_api");
      vid.loop = true;
  }
  else
    console.log("can't tell if video has audio");
});
</script>

Any help?

Fix your braces. Every "if" and "else" result needs to be wrapped in curly braces.

Technically, single-line blocks do not, but it's good practice. Multiple line blocks have to be wrapped, or they'll evaluate. In particular, I'm looking at several vid.loop = true lines that aren't in any braces!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM