The event listener continues to throw an error when attempting to play audio

I'm encountering an issue with triggering audio in my window's load listener function.

var audio = new Audio();
audio.src = "assets/silence.mp3";
audio.load();
document.getElementById("body").addEventListener(
  'touchstart',
  function(evt){ audio.play(); audio = 0; },
  {capture:false,once:true,passive:true}
);

When using Chrome on Android (with remote debugging open), I tap the screen and it attempts to play the audio. However, it fails and outputs this error to the console:

(index):65 Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

I'm wondering how else I can trigger audio in a way that ensures the user initiates it, if not through a user interaction event listener.

Answer №1

It seems that using the event touchstart does not qualify as a "user interaction" in terms of preventing auto-play.

The solution is to replace it with the event click.

One issue that is still causing frustration:

I am utilizing this particular code snippet to quickly enable audio playback on a webpage so that the HTML5 game can play audio without being blocked by the browser.

However, because it requires a full "click" event instead of a "touchstart" event, any audio that should be triggered on "touchstart" will be missed (the first time it should have been triggered). It appears that 1. there is no way to work around this to achieve my desired outcome, and 2. if you are able to simply listen for a "click" on the entire document, it is not effectively preventing unwanted audio.

If anyone has a better solution, I am open to changing the "correct answer" to that suggestion.

Answer №2

While creating a virtual piano for a website, I encountered a similar issue where the browser loaded the piano immediately upon loading the page. This meant users could start playing the keys by simply touching the screen before even clicking anything. To address this, I implemented a starting screen with a play button to initiate the game. This solution required users to actively click on the button before they could start using the virtual piano keys.

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

Maximizing Button Functions in One Activity

Managing 56 toggle buttons along with 8 regular buttons on a single activity can be tricky. While handling the 8 regular buttons is not a problem using a single onClickListener class, dealing with the toggle buttons presents a challenge. Using a switch ca ...

When initializing a local scope property as null in Angular.js, it may end up being undefined

Recently, I created a custom Angular directive. <location zipcode="35423" cityname="" statecode=""></location> Within the directive, I defined the following: scope: { zipcode: "@", cityname: "@", ...

Creating personalized labels with Vue.js and Element UI radio button components

When using Element UI radio buttons on a form, I am attempting to personalize the label for each selection. Each radio button includes a prop called "label" where I can input my label text successfully. The problem arises when I need to apply a different s ...

Utilizing Laravel to Showcase Google Maps with Custom Markers Generated from MySQL Data

As I work on developing a web application that involves integrating Google Maps and multiple markers, I encountered an issue this morning. Initially, I successfully implemented the map with markers from a single database table. However, my goal now is to ...

Engaging in payment processing

Currently facing a significant dilemma. I am utilizing Stripe as my payment gateway, which functions in a two-step process: Collect billing information to generate a token Charge the client using the generated token The issue arises because the token ca ...

What is the best way to eliminate spaces, commas, and periods from a variable in javascript?

After attempting var res = str.replace(/ |,|.|/g, ""); and var res = str.replace(/ |,|.|/gi, "");, I'm still puzzled as to what I might be missing. var str = "Text with comma, space, and period."; var res = str.replace(/ |,|.|/g, ""); document.writ ...

The execution of JQuery/Javascript is restricted to only the initial condition within a Visualforce page utilizing the apex:outputpanel tag

After using only JavaScript for some time, I decided to try out jQuery. However, I'm facing an issue with executing a jQuery function. It seems that only the first condition in my code (the first IF) is being executed, while the second one (the second ...

Functionality of local data storage

I'm currently exploring the capabilities of the localStorage feature. Let's say I have a large JSON object stored using localStorage. I need to share this data with the testing team for review. However, if I try to display the stored data on an H ...

the step-by-step guide to effortlessly uploading an image with ajax

How can I upload an image without the page refreshing? Whenever I hit submit to upload an image, my page still refreshes. It works fine when submitting plain text, so what could be wrong with my ajax code? test.php <div class="preview_d_p" id="preview ...

Using Bootstrap4 tagsinput, removing a tag: detecting for AJAX fulfillment and then reversing the action

Utilizing tagsinput in conjunction with bootstrap4, my goal is for the user to be able to delete a tag by clicking on the 'x' button. Upon deletion, an ajax request is sent to the server to verify if the user has permission. The server will respo ...

Solving templateUrl resolution of directives in Angular with RequireJS

Currently, I am using AngularJS and RequireJS in my single-page application (SPA). To organize imports efficiently, I rely on RequireJS. With RequireJS, I can utilize features like baseUrl to resolve import paths seamlessly. Now, I wish to apply the same r ...

Hold off until the script is successfully downloaded and executed, then patiently wait for the DOM to finish loading

I'm facing a challenge with running Javascript conditionally without it being in requirejs form. The script is located on the same server/domain as the requesting page, where an ajax call needs to be made. Is there a foolproof way to ensure that an a ...

Exploring the use of the Next.js page router for implementing internationalization (i18

I need assistance implementing Dutch and English language translations for my entire website. Can anyone provide guidance? I have tried using i18n localizely, but it only works for individual pages. I am looking to implement translations on a larger scale ...

Nodejs/Express: The view "error" could not be found in the views directory

I recently made the switch from Jade to EJS as my template engine for my Node.js application. However, when I try to run my app.js file with the EJS template, I am encountering a series of error messages that say "Failed to lookup view 'error' in ...

Firebase and Angular 7 encountered a CORS policy block while trying to access an image from the origin

I am attempting to convert images that are stored in Firebase storage into base64 strings in order to use them in offline mode with my Angular 7/Ionic 4 application! (I am using AngularFire2) However, I encountered an error message stating: Access to i ...

Using JQuery to make an AJAX request with URL Rest path parameters

Currently, I have a REST service located at /users/{userId}/orders/{orderId} and I am looking to make a call to it using JQuery. Instead of simply concatenating the IDs like this: $.get( 'users/' + 1234 + '/orders/' + 9876, fu ...

Steps to automatically navigate to a specific Div upon page initialization

Can someone help me understand why my code is scrolling to a div and then returning back to the top of the page? $("#Qtags").click(function(){ $('html, body').animate({'scrollTop' : $($(this).attr('href')).offset().top}, ...

Using Three.js to position objects along a curve and rotate them toward the center of a circle

I'm working on developing a sleek VR menu that presents menu items in a curved column below the camera as the user looks down. The challenge is to have the items rotated towards the camera while appearing uniform. Here's what I've come up w ...

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...