Ways to rouse a dormant AudioTracks feature

When I click a button, I am able to get the correct value of AudioTracks.length. However, without clicking the button, I am unable to retrieve this value. Take a look at my code below. It works at line (B) but not at (A). Can you help me understand why and how I can make it work at (A)? I have a feeling that there's some basic concept I'm missing here, so any assistance would be greatly appreciated. Thank you!

[My code]

<!DOCTYPE html>
<html>
    <body>
        <h3>Please use a browser supporting AudioTracks property. See [Note] for details.</h3>
        <video id="video" controls>
            <source src="https://www.w3schools.com/tags/mov_bbb.mp4"></source >
        </video>
        <button onclick="myFunction()">Click (myFunction)</button>
        <script>
            console.log("(A) = " + video.audioTracks.length );// (A) = 0
            function myFunction() {
                console.log("(B) = " + video.audioTracks.length );// (B) = 2
            }
        </script>
    </body>
</html>

[Note] The audioTracks property is not supported in any major browsers. It is supported in Chrome beta by enabling "enable-experimental-web-platform-features" in chrome:flags.

  1. Download Chrome beta Version 107.
  2. Type "chrome://flags/" in the address bar to see "Experiments" page.
  3. Enable "#enable-experimental-web-platform-features".

[Reference] https://caniuse.com/audiotracks

Answer №1

In order to access any information from a resource, such as audioTracks or .duration, you must wait for the resource to be preloaded first.

This can be achieved by waiting for either the loadedmetadata event or the canplay event.

const vid = document.querySelector("video");
vid.onloadedmetadata = (evt) => {
  console.log(vid.audioTracks);
};
<video controls>
  <source src="https://www.w3schools.com/tags/mov_bbb.mp4">
</video>

Answer №2

After reviewing your code, I decided to test it out by running the following:

<!DOCTYPE html>
<html>
    <body>
        <h3>Please use a browser supporting AudioTracks property. See [Note] for details.</h3>
        <video id="video" controls>
            <source src="https://www.w3schools.com/tags/mov_bbb.mp4"></source >
        </video>
        <button onclick="myFunction()">Click (myFunction)</button>
        <script> 
            console.log("(A)"+document.getElementById("video").audioTracks);// (A) = 0
            function myFunction() {
                console.log("(B) = " + video.audioTracks.length );// (B) = 2
            }
        </script>
    </body>
</html>

Note: I overlooked the need to restart my browser in order to see the effect

@Kaiido's advice is accurate - simply waiting for the metadata to load is sufficient.

I made a slight adjustment to your video element like this:

<video id="video" onloadedmetadata="myFunction()" controls=true>
            <source src="https://www.w3schools.com/tags/mov_bbb.mp4"></source >
</video>

Upon loading the video, it displayed (B) = 2 without needing me to click the button.

If you want to run code only after everything has loaded, you can utilize the onloadedmetadata attribute. Alternatively, if there are multiple elements to load, consider using

window.requestNewAnimationFrame(runningFunc)
to ensure all elements are loaded before proceeding.

I hope this explanation resolves any doubts and corrects any errors I may have made.

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

Using a wildcard (*) to select elements with JQuery

I'm just starting to learn about JQuery and could use some help. I want to select multiple elements but I only know part of their Ids: for example: <div id="element32422455">Some content</div> <div id="element68475124">Some content& ...

Is it necessary for a component to disconnect from the socket io server upon unmounting?

Is it best practice for a React component to automatically disconnect from a socket.io server when it unmounts using the useEffect hook? If so, could you provide an example of the syntax for disconnecting a React component from a socket.io server? ...

The Jade variable assignment variable is altered by the Ajax result

Seeking a solution to update a Jade variable assigned with the results of an ajax post in order for the page's Jade loop to utilize the new data without re-rendering the entire page. route.js router.post('/initial', function(req, res) { ...

Is there a way to make the checkbox and corresponding text display on a single line within my code snippet?

Bootstrap text-truncate is causing the checkbox and text to appear on separate lines in the following example. How can I adjust it to have the text right after the checkbox? <!DOCTYPE html> <html> <head> <meta charset="UTF-8" / ...

Alert: Zone.js has identified that the ZoneAwarePromise '(window|global).Promise' has been replaced with polyfills. Kindly address this issue

Recently, I updated my Angular application from version 8 to 9. After updating the packages and successfully compiling the application, I encountered an error message in the Chrome browser console: Error: Zone.js has detected that ZoneAwarePromise `(wind ...

sending data from an AngularJS application to an MVC controller in JSON format containing multiple arrays

Currently, I am working on a project that involves using AngularJS and MVC. I am transferring data from an AngularJS controller to my MVC controller using $http.post(). At the moment, I am using a single object or JSON array to retrieve data as follows: pu ...

Clear a variable that was sent through the post method in an ajax call

Within my JavaScript file, I have the following Ajax code: // Default settings for Ajax requests $.ajaxSetup({ type: 'POST', url: path + '/relay.php' + '?curr=' + currency + "&ver=" + Ma ...

Ajax request terminates once PHP has looped for a specific duration of time (2 minutes)

My challenge involves a button that is responsible for checking over 300 posts for a specific value and other conditions using about 20 if-else statements. Strangely, the ajax call initiated by this button halts after completing around 73 loops within a sp ...

[Error: hex is not recognized as a valid function]

Snippet of my Code: jwt.verify(token,JWT_SECRET,(err,payload)=>{ if(err){ res.status(401).json({error:"You must be logged in"}) } const _id = payload._id collection_name.findById(_id) .then(userdata=>{ req.user = p ...

AntD Functional Component with Row Selection Feature

Is there a way to retrieve the key of a single element in the table instead of getting undefined? How can I extract the id? Check out this link for more information. const [select, setSelect] = useState({ selectedRowKeys: [], loading: false, }); ...

Does the modularization of code impact the performance of the react-app?

The client provided me with a React app that includes an index.jsx file where 90% of the coding has been completed. To prevent getting stuck in Scroll Limbo, I have started breaking down the code into modules for each specific requirement. These include ...

Troubleshooting the issue: React Native Redux not navigating correctly using API IDs

Lately, I've been utilizing Redux for my application and it's been going well. However, I recently encountered a roadblock that has halted my coding progress temporarily. My current challenge involves creating a navigation system using the ID of ...

The UTF-8 data sent by JQuery AJAX is not being correctly processed by my server, but only in Internet Explorer

When I send UTF-8 Japanese text to my server, it works fine in Firefox. Here are the details from my access.log and headers: /ajax/?q=%E6%BC%A2%E5%AD%97 Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Content-Type application/x-www-form-urlencoded; char ...

Express server experiences empty body when using the Fetch POST method

Executing a POST request from my browser client looks like this: const post = async (url, body) => { try { const response = await fetch(url, { method: `POST`, headers: { 'Conte ...

Is it possible to generate an array of all matches found by a regular expression

I am trying to utilize the match-all package in order to match CSS selectors and generate an array of all of them. Here is the code snippet. const matchAll = require("match-all"); let s = `.u-br, .u-nr { blah blah } .u-tr { blah .blah }`; consol ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

Using JavaScript to override a specifically declared CSS style

In the process of working with a database, I come across HTML that includes "spans" colored in different shades. An example would be: <div id="RelevantDiv">the industry's standard <span style="background-color: red">dummy text ever since ...

What is the method for obtaining the worldwide location of a vertex on a skinned mesh in Three.js?

In the realm of Three.js, we've recently acquired the ability to determine the global position of a vertex in a non-skinned mesh thanks to insights from this question. Now, the query arises - how can one ascertain the global position of a vertex in a ...

Issue in React: Unable to choose options from a dropdown menu once a value attribute has been assigned to the component's state

One issue I encountered with my React component that renders a dropdown menu is that although it successfully re-renders the value when new props are received, it disables the option to select a different value. This behavior occurs because I have set th ...

Having trouble with the Document.createElement function not functioning properly when trying to download a

ISSUE While my PDF download feature functions properly in Chrome, it encounters difficulty when attempting to work in IE 11/10/9. When using IE, I receive a security warning prompt. After selecting Yes to allow the download, nothing happens. SOURCE CODE ...