Tips for managing Uncaught (in promise) DOMException: An interruption in the play() request due to a pause() call

My code in the aspx page allows for playing audio files of wav format within the browser. However, I have encountered an issue where wav audios are not playing in Chrome browser, while they work in Firefox. How can I address this exception?

<script>
    window.onload = function () { document.getElementById("audio").play(); }
    window.addEventListener("load", function () { document.getElementById("audio").play(); });
</script>

<body>
    <audio id='audio' controls autoplay>
        <source src="Sounds/DPM317.wav" type="audio/wav" />
        Your browser does not support the audio element.
    </audio>
</body>

Answer №1

Google Chrome has updated its autoplay policy, which means you may need to adjust your code accordingly. You can find more information here:

var promise = document.querySelector('audio').play();

if (promise !== undefined) {
    promise.then(_ => {
        // Autoplay started!
    }).catch(error => {
        // Autoplay was prevented.
        // Display a "Play" button for user interaction.
    });
}

Answer №2

Consider implementing a callback similar to this within the catch block:

document.getElementById("sound").load().catch(function() {
    // take appropriate action
});

Answer №3

Not sure if you still need this information, but I'll leave my comment here just in case it helps someone else out there. I experienced a similar issue and found a solution suggested by @dighan on bountysource.com/issues/ that worked for me.

Here is the code snippet that resolved the problem for me:

var media = document.getElementById("YourVideo");
const playPromise = media.play();
if (playPromise !== null){
    playPromise.catch(() => { media.play(); })
}

Although it still triggers an error in the console, at least the video plays now :)

Answer №4

  1. Ensure that all new browsers support video autoplay, but only when muted. To achieve this, use the following code:

<video autoplay muted="muted" loop id="myVideo">
  <source src="https://w.r.glob.net/Coastline-3581.mp4" type="video/mp4">
</video>

Consider implementing a solution similar to this.

  1. Make sure the URL of the video aligns with the SSL status of your website. If your site is running on HTTPS, the video URL should also use HTTPS, and the same goes for HTTP.

Answer №5

My problem was resolved by adding the muted="muted" property to the HTML5 audio tag.

Answer №6

I am currently running Chrome version 75.

To mute a video, simply add the muted property to the video tag:

<video id="myvid" muted>

Then use JavaScript to play the video and set the muted attribute to false:

var myVideo = document.getElementById("myvid");
myVideo.play();
myVideo.muted = false;

Note: User interaction is required for this to work (at least clicking anywhere on the page).

Answer №7

Adding to Shobhit Verma's point, I would like to mention that he highlighted the need to mute the players in Chrome (Opera for me) for autoplay to work. Interestingly, even if you increase the volume after loading, the video will still play... It's reminiscent of those anti-pop-up mechanisms that sneak into your code as invisible frames. The php-echoed html and javascript snippet looks something like this: A 10-second setTimeout function is applied on the body tag upon load, which sets the volume to maximum, initializes a video with autoplay and muted='muted' attribute.

echo "<body style='margin-bottom:0pt; margin-top:0pt; margin-left:0pt; margin-right:0pt' onLoad=\"setTimeout(function() {var vid = document.getElementById('hourglass_video'); vid.volume = 1.0;},10000);\">";
    echo "<div id='hourglass_container' width='100%' height='100%' align='center' style='text-align:right; vertical-align:bottom'>";
    echo "<video autoplay {$muted_code} title=\"!!! Pausing this video will immediately end your turn!!!\" oncontextmenu=\"dont_stop_hourglass(event);\" onPause=\"{$action}\" id='hourglass_video' frameborder='0' style='width:95%; margin-top:28%'>";

Answer №8

For me, I found myself in a situation where I needed to wait for a user interaction before proceeding. To achieve this, I implemented a listener for either a click or touchend event.

const isTouchDevice = navigator.maxTouchPoints || "ontouchstart" in document.documentElement;

function initiatePlayback(){
    audioElement.play()
}

document.body.addEventListener(isTouchDevice ? "touchend" : "click", initiatePlayback, { once: true });

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

An introduction to integrating Paged.js with Vue.js3

index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> < ...

Looking to convert a jQuery function to plain JavaScript code?

Struggling with my homework, I must apologize for any mistakes in my English. My task involves creating a chat using node.js and I found some code snippets on a website "" which I used successfully. The issue now is that the chat relies on old jQuery libr ...

Using JavaScript to bring in npm packages

My understanding of javascript modules is still lacking. I recently embarked on a new project that required a library from npm. https://www.npmjs.com/package/random-color-pair After running npm i random-color-pair This created a "node modules" folder wh ...

Leveraging EHLAPI32 within C# for integration with RUMBA as the selected emulation provider

Could someone provide me with a tutorial on utilizing EHLAPI32.dll in C# with RUMBA as the emulation provider? I need to extract data from a mainframe. ...

The issue of JavaScript text not being able to be selected persists in Chrome and Internet Explorer

While the text appears fine in Firefox, it remains selectable in Chrome and Internet Explorer. Is there a way to work around this issue? The code snippet was borrowed from another post (which I cannot locate at the moment) so it may be outdated? // To pre ...

Searching for a specific string within an array using JavaScript: tips and tricks!

I have a variable which looks like this: var d; d = [{'category': 'Hourly Report','from_start_datetime': '2013','format': 'yyyy-mm-dd hh:ii:ss', 'id': 'dateRangeTo'}] When I ...

Passing large arrays of data between pages in PHP

I'm facing a challenge where I need to pass large arrays of data between pages. Here's the situation: Users input their Gmail login details in a form, which is then sent to an AJAX page for authentication and contact retrieval. If the login fail ...

Ways to clear TextField status

My question is about a Textfield. In the case where the state is null but the text field value is showing in the Textfield. <TextField style={{ width: '65%'}} id="standard-search" ...

Issue with Gridview CheckboxList in Edit Mode due to unset values

After weeks of intermittent work and numerous internet searches, I am still unable to align my goals with the results when it comes to handling boolean fields in SQL Server. I have five boolean fields that I can update and display in a label field without ...

Is Node.js compatible with Mysql Schema?

Currently working on a web service using Node.js, I've decided to switch from MongoDB to MySQL. With MongoDB, I could easily create a schema using Mongoose: var mongoose = require('mongoose'); var Schema = mongoose.Schema; mongoose.connect ...

Console displays null as the attribute value

When I check the console, I notice that the data-postid attribute is displaying 'null'. What could be causing this issue? I would like to view the data-id in the console when clicking on the button with the id modal-save. I have reviewed my cod ...

Error message: Please provide an expression with const in React JS component

Can you assist me with this issue? I am trying to determine if the user is registered. If they are registered, I want to display the home URL, and if they are not registered, I want to display the registration URL. To do this, I am checking the saved dat ...

Executing a node.js function within an Angular 2 application

Currently, I am running an Angular2 application on http://localhost:4200/. Within this app, I am attempting to call a function located in a separate node.js application that is running on http://localhost:3000/. This is the function call from my Angular2 ...

How can I iterate through multiple rows in JavaScript?

Feeling stuck, the simple yet dreaded for loop has become my nemesis and I could really use some guidance. Currently, I have a Google sheet with 3 rows (excluding headers) and 8 columns. As users input data via a web app, the number of rows will dynamicall ...

Shader in THREE.js designed to accommodate ControlNet for normal calculations

Is there a way to adjust this standard shader to bypass the preprocessor for controlnet? Check out the code here: https://jsfiddle.net/lunchie/mpuanxL3/4/ skinnedMesh.material = new THREE.ShaderMaterial( { vertexShader: [ '# ...

Update the styling for the second list item within a specified unordered list class instantaneously

Looking to emphasize the second list item (li) within a selected dropdown list with a designated unordered list class of "chosen-results". <div class="chosen-container chosen-container-single select-or-other-select form-select required chosen-proc ...

Retrieving specific elements in JavaScript from a JSON file

I am attempting to extract information from a JSON file with the following data: [3000,2500,6000,2200,5000,1300]. The file is named data.txt. To achieve this, I initialize an empty array in my code. Subsequently, I utilize the $.getJSON function by passi ...

An issue occurred while trying to process the XHR response text for files of a large size

I've been using the Jquery fineUploader to upload files and I've encountered the following error message: 404 - File or directory not found. This error occurs when trying to upload files larger than 30MB, while smaller files below 30MB upload w ...

Guide on how to append to a nested array within a React component?

I have been working on a prototype for a Slack clone. I encountered an issue where when I attempt to add a message to the array this.state.channels.message, it ends up being added as a new object in the array channels: EXPECTED RESULT class App extends R ...

Is it possible to have an object nested within a function? How about a function within a function? I'm determined to grasp

0 Can someone explain to me how the function express() works? I'm having trouble understanding how you can call a function when stored in a variable like const app = express(); Then calling a function like listen() as if it were an object: app.list ...