Align audio and video elements in HTML5 using JavaScript

I am facing a situation where I have two files - one is a video file without volume and the other is an audio file. I am trying to play both of these files using <audio> and <video> tags. My goal is to make sure that both files are ready to play before starting the video, otherwise I want to wait until they are both ready. However, the canPlay method is not working as expected because it can only check for readiness of one file at a time.
Thanks

UPDATE

  audio.addEventListener('canplay',function(){
    audio.play();
    video.play(); 
  });

  video.addEventListener('canplay',function(){
    audio.play();
    video.play(); 
  });  

I tried this approach but it did not work as intended. The problem is that when one of them starts playing, it triggers the play for both files simultaneously, regardless of whether the other file is ready or not, due to the use of play() for both.

Answer №1

Monitor the canplaythrough event for both elements and if both are ready, initiate playback on both.

The canplaythrough event is triggered when the browser can play the media content without interruptions due to buffering.

Here's a way to achieve this:

var audioReady = false,
  videoReady = false;
audio.addEventListener('canplaythrough', function() {
  audioReady = true;
  playAll();
});

video.addEventListener('canplaythrough', function() {
  videoReady = true;
  playAll();
});

function playAll() {
  if (audioReady && videoReady) {
    audio.play();
    video.play();
  }
}

Note: You can also use promises to accomplish the same behavior.

Check out this alternative approach:

var audioPromise = new Promise(function(resolve) {
  audio.addEventListener('canplaythrough', function() {
    resolve();
  });
});
var videoPromise = new Promise(function(resolve, reject) {
  video.addEventListener('canplaythrough', function() {
    resolve();
  });
});

function playAll() {
  audio.play();
  video.play();
}
Promise.all([audioPromise, videoPromise]).then(playAll);

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

Why is Python BeautifulSoup's findAll function not returning all the elements in the web page

I am attempting to retrieve information from the following URL . Displayed below is the code I have developed. import requests from bs4 import BeautifulSoup url_str = 'https://99airdrops.com/page/1/' page = requests.get(url_str, headers={&apo ...

Tips for moving a title sideways and adjusting the bottom section by x pixels

I am seeking to accomplish a design similar to this using CSS in order to create a title of <h1>DISCOVER <span>WEB 3</span> DIMENSIONS</h1>. How do you recommend achieving this? Thank you, I have searched on Google and asked frie ...

Unusual Box-shadow glitch experienced exclusively when scrolling in Chrome 51

While working on my website, I encountered a peculiar issue with the box-shadow in Chrome 51. My site has a fixed header with a box-shadow, but when I scroll up or down, the box-shadow leaves behind some marks (horizontal gray lines): https://i.stack.imgu ...

Sharing and showcasing files directly from a local directory

Recently diving into NodeJS and web development, I've successfully used multer to upload a single file within my web application. The file gets uploaded to my "uploads" folder flawlessly, and now I'm planning on storing the file path in my databa ...

AngularJS allows for the creation of cascading dropdown selects, where the options in the second select

I'm struggling to access the version data stored in the server model, but it's not cooperating. My suspicion is that when the page loads, the initial data from the first select isn't available yet because it hasn't technically been sel ...

Utilizing jQuery's nextUntil() method to target elements that are not paragraphs

In order to style all paragraphs that directly follow an h2.first element in orange using the nextUntil() method, I need to find a way to target any other HTML tag except for p. <h2 class="first">Lorem ipsum</h2> <p>Lorem ipsum</p> ...

Issue with MUI-table: The alternate rows in the MUI table component are not displaying different colors as intended

Struggling to apply different colors for alternate table rows function Row(props) { const { row } = props; const StyledTableRow = styled(TableRow)(({ theme }) => ({ '&:nth-of-type(odd)': { backgroundColor: "green", ...

javascript design pattern - achieving unexpected outcome

In the code snippet provided, the variable a is turning out to be undefined. Are you expecting it to display the parameter value passed in the parent function? function test(a) { return function(a) { console.log('a is : ' + a); // Ou ...

A fragmented rendering of a gallery featuring a CSS dropdown menu

Hey there! I'm a newbie coder seeking some assistance. Recently, I stumbled upon a tutorial online that taught me how to create a drop-down menu. However, whenever I hover over "Gallery" on my website, things go haywire and the layout gets all messed ...

What are the steps to modify the text color in WKWebView?

I've customized my ViewController to include a WKWebView, where I load my content from both .html and .css files. The result resembles a controller for reading books within the Apple Books app. do { guard let filePath = Bundle.main.path(fo ...

npm unable to locate the specified file

I'm currently following a tutorial on creating a Google Maps clone. After completing the build, I tried running the npm start command but encountered the following errors: npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\m ...

What steps do I need to take to ensure the CSS hover effect functions properly?

After conducting a simple test underneath the main divs, I found that it works as intended. However, the primary one is not functioning properly. I attempted to apply the class "services-icon" to the div containing the image, but it still did not work. I ...

Java Library for Converting HTML to Textile Format

I have a requirement to convert a String from HTML format to Textile format. After researching various libraries such as Textile4J, Textile-J, JTextile, and PLextile, I found that none of them offer the specific functionality I need. Although they do prov ...

Using Jest or Mocha alongside Vue: Uncaught SyntaxError: Cannot use import statement outside a module

Update: This post has undergone multiple edits, please refer to this new Stackoverflow post for a clearer explanation of the issue: SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial I have been searc ...

Having trouble with accessing the upvote/downvote input within a Django template

Currently, I'm trying to retrieve upvote/downvote data from a Django template in the following manner: <form method="POST" action="{% url 'vote' %}" class="vote_form"> {% csrf_token %} <input type="hidden" id="id_value" name="valu ...

Transform your image using the Bootstrap framework

I am attempting to create a similar banner using bootstrap. You can view the demo of the banner here. https://i.stack.imgur.com/JXLNY.png I'm struggling to understand how to achieve this in bootstrap 3 and where to begin. Should I use rows and colum ...

The Flutter image blurs into a striking combination of red and black as the screen dimensions are altered

https://i.stack.imgur.com/YeZa6.png Hello everyone, we are facing an issue with Flutter web. Here's what's happening: When we use flutter run -d chrome --web-renderer canvaskit and flutter run -d chrome --web-renderer html, nothing changes. If ...

The reload button retains functionality while being present within an Angular2 form, allowing for a seamless user experience. The

After some observation, I have realized that when a button is placed inside a form but has no connection or function related to the form, such as a back or cancel button, it unexpectedly reloads the entire page. For instance, let's consider having ...

Issue: Unhandled promise rejection: BraintreeError: The 'authorization' parameter is mandatory for creating a client

I'm currently working on integrating Braintree using Angular with asp.net core. However, I've encountered an issue that I can't seem to solve. I'm following this article. The version of Angular I'm using is 14, and I have replicate ...

Exploring the Integration of jQuery AJAX in a Contact Form

I would like to incorporate AJAX functionality into a contact form. Here is the current code I have... $("#contact_form").validate({ meta: "validate", submitHandler: function (form) { $('#contact_form').hide(); ...