Ways to confirm if a video has sound

There is a video that has an audio track, yet the volume is not zero or muted, resulting in the video being silent. I am looking for a way to determine if a video is audible so that I can perform specific functions accordingly.

I came across a method to check if a video contains an audio track from @upuoth, which works on most browsers except IE10+. Additionally, @brefd.it's method works for IE10+ but I need guidance on how to implement his code.

@upuoth's script


 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");
});

@brefd's script


function hasAudio (video) {
return video.mozHasAudio ||
Boolean(video.webkitAudioDecodedByteCount) ||
Boolean(video.audioTracks && video.audioTracks.length);
}

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

I have set up three video clips: one with audible audio, one without any audio, and one that has an audio track but is not audible. The provided code only works for the first two clips and not the third one. To display an alert of "not audible" when playing the third clip, you can use the code from this JSFiddle link.

Answer №1

Here's the combined code from above that you can utilize in your JSFiddle:

document.getElementById("myVideo").addEventListener("loadeddata", function() {
    if (typeof this.webkitAudioDecodedByteCount !== "undefined") {
        if (this.webkitAudioDecodedByteCount > 0)
            alert("This video contains audio");
        else
            alert("no audio track found");
    } else if (typeof this.mozHasAudio !== "undefined") {
        if (this.mozHasAudio)
            alert("This video has an audio track");
        else
            alert("No audio detected");
    } else if (typeof this.audioTracks !== "undefined") {
        if (this.audioTracks && this.audioTracks.length)
            alert("contains audible audio");
        else 
            alert("audio not audible");
    } else
        alert("Unable to determine audio presence");
});

It may be challenging to identify "not audible" audio tracks using the given methods.

Answer №2

There are various methods to determine if a video file contains audio or not, including utilizing the mozHasAudio,

video.webkitAudioDecodedByteCount
, and video.audioTracks?.length properties of the video element. It's a straightforward approach...

const video = component.node.querySelector("video");
video.onloadeddata = function() {
    if ((typeof video.mozHasAudio !== "undefined" && video.mozHasAudio) ||
        (typeof video.webkitAudioDecodedByteCount !== "undefined" && video.webkitAudioDecodedByteCount > 0) ||
        Boolean(video.audioTracks?.length)) {
        console.log("This video contains audio tracks.");
    } else {
        console.log("This video does not have any audio tracks.");
    }            
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting the "status" of a queue: A step-by-step guide

I created a function to add a job to the queue with the following code: async addJob(someParameters: SomeParameters): Promise<void> { await this.saveToDb(someParameters); try { await this.jobQueue.add('job', ...

What is the best way to showcase response information on the website interface?

Recently, I have been utilizing GET requests to the github API: axios.get('https://api.github.com/users/roadtocode822') .then(function (response) { console.log(response.data); }) Successfully retrieving the response data. This particula ...

Sparse planeBufferGeometry in THREE.js is a specialized type of geometry that

I am currently working with a file that contains sparse elevation data derived from GPS information. I have been utilizing this data to fill a PlaneBuffer array with elevations. var vertices = new Float32Array( (grid.NCOL*grid.NROW) * 4 ); for (var i = 0, ...

The data type 'string[]' cannot be assigned to the data type '[{ original: string; }]'

I have encountered an issue while working on the extendedIngredients in my Recipe Interface. Initially, I tried changing it to string[] to align with the API call data structure and resolve the error. However, upon making this change: extendedIngredients: ...

Angular Build Showing Error with Visual Studio Code 'experimentalDecorators' Configuration

Currently experiencing an issue in VSC where all my typescript classes are triggering intellisense and showing a warning that says: "[ts] Experimental support for is a feature that is subject to change in a future build. Set the 'experimentalDeco ...

Is the use of div:after content really affecting the width? I am having trouble getting my transition to work

Here is a simple code snippet that represents my actual code: #myDiv { background: black; color:white; float:left; min-width:45px; max-width:450px; -webkit-transition: all 1s ease-in-out; transition: all 1s ease-in-out; } #myDiv:hover:after { width ...

How to prevent mouse click events in Three.js after interacting with an HTML overlay

Encountering an issue with Three.js: I have created my own HTML user interface as a simple overlay. However, I am facing a problem where the mouse click does not reset when I interact with elements on this overlay. Specifically, when I click on the "Came ...

The JavaScript creates a select box, but the value does not get sent when the form is submitted

When a user selects a value from the first select box, a second select box is dynamically created using JavaScript. This JS triggers a PHP file to query a MYSQL database for relevant items based on the initial selection. The issue I am facing is that the ...

Is it possible to dynamically assign a template reference variable to a newly created DOM element in TypeScript?

After creating a DOM element with this.document.createElement('h1'), I am looking to insert the element into a section tag using a template reference variable (myTRF), similar to the example below: <section> <h1 #myTRF>This is my he ...

React - Error occurred when parsing module: Unexpected Token. It is recommended to use a suitable loader to manage this file format

As a beginner in using React, I might be making obvious mistakes and I apologize for that. After researching similar bugs on various platforms like StackOverflow and GitHub, I couldn't find a solution that works for my specific issue. Here is the erro ...

Reinitializing the database with Cypress (postgresql)

When populating the database, I intentionally do it partially for certain tests. However, after completing all tests, I would like to reset the database in order to avoid any complications that may arise during the next populate process. How can I efficien ...

Optimizing the performance of J2EE web applications

I am currently working on enhancing the performance of my web application. The application is java-based and is hosted on an Amazon cloud server with JBoss and Apache. One particular page in the application is experiencing a slow loading time of 13-14 sec ...

The package-lock file may vary depending on the npm version being used

I am experimenting with a new typescript react app that was created using CRA. I am running @6.4.1 on one PC and an older version on another. Interestingly, the newer version installs dependencies with an older version instead of the expected new one. ...

Is the row removed from the table after successful deletion?

I am struggling to remove the deleted row from the table. The code I tried is not working as expected. Here is the scenario: When a user clicks on the delete link/button, it sends a delete request and removes the data from the Database. After successful de ...

The functionality of Object.assign in REACT is producing unexpected and incorrect results

Hey everyone, I have a project in React with 3 components. My goal is to extract the state from these 3 components and combine them into one JSON object on a final page. The components are not nested as child and parent, so my workaround was to set the st ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...

The form I created retrieves select options via an ajax call, but after saving, the post values are not displaying as expected

I have created a form with the following HTML code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Populate City Dropdown Using jQuery Ajax</title> <script type="text/javascript" src="h ...

Tips for updating state in response to changes in props

I am working on a project where I have a Parent component that renders a large form. The Parent component has child components Child1 - Child4, which are responsible for rendering input fields. Whenever the props of the Parent component change, I need to ...

Guide on Retrieving the Current URL in NodeJS

Currently, I am utilizing express in conjunction with node.js. In my setup, the following code is present: app.get('/callback', async function (req, res) { Whenever a user reaches the callback section of my website, I expect to receive the req ...

the onreadystatechange function is not being triggered

When trying to call the show_Message function, I expected an alert box to appear. However, the onreadystatechange is not working as expected. All other alert boxes are functioning properly. Below is my JavaScript function: function send_Message(){ var ...