iPad is playing the incorrect file when using .play(). Any ideas on how to fix this issue?

Currently, I am developing a web application that involves a div element with dynamic text content that changes based on user interactions. To enhance the user experience, I decided to incorporate audio elements by creating an array containing corresponding sound files:

var phrases=['Please hand me the awl.','etc1','etc2','etc3'];
var phrasesAudio=['awl.mp3','etc1.mp3','etc2.mp3','etc3.mp3'];

With each user action, a 'counter' variable is incremented, and both arrays are accessed using this counter to retrieve the appropriate text and audio file.

var audio  = document.createElement("audio"),
canPlayMP3 = (typeof audio.canPlayType === "function" && audio.canPlayType("audio/mpeg") !== "");
function onAction(){
correct++;
document.getElementById('speech').innerHTML=phrases[correct];
if(canPlayMP3){
    snd = new Audio(phrasesAudio[correct]);
}
else{
    snd = new Audio(phrasesAudioOgg[correct]);
}
snd.play();
}

While this implementation generally works fine (especially in regular browsers), I have encountered issues specifically on the iPad target device. After a few iterations, the text updates correctly but the audio glitches by repeating previous sound files. Upon debugging, it appears that although the code attempts to play a specific file like screw.mp3, it actually plays another like screwdriver.mp3. This lagging behavior makes me suspect that the issue lies within my use of the .play() method. I attempted resetting the audio object between each play with snd=null;, but saw no improvement. Any suggestions on how to troubleshoot this problem? As a novice in working with audio elements, I welcome any guidance or tips. Thank you.

Update: I also experimented with setting the audio source using snd.src (referencing https://wiki.mozilla.org/Audio_Data_API), however, this resulted in no audio playback at all.

Answer №1

When working with an iPad, it is important to remember to call snd.load() before snd.play(). Failure to do so may result in unexpected behavior.

For additional information and insights, you can visit:

Autoplay audio files on an iPad with HTML5

EDIT - following a comment from the OP:

You can find a useful tip on stopping currently playing media at https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox

var mediaElement = document.getElementById("myMediaElementID"); 
mediaElement.pause(); 
mediaElement.src = ""; 

After performing the above actions and setting the correct src, using load() and play() should work smoothly.

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

Adding JQuery to a running webpage using the DOM and Opera browser add-ons

I'm currently working on an Opera Extension and I have a question. Is there a way to use the includes folder in order to directly inject jQuery into the live HTML of a webpage? For example, can I change the background color of the DOM to black? If ...

Code in JavaScript often includes the use of variables to store and manipulate data

Do these blocks of JavaScript code serve the same purpose? // First Code Sample var first = prompt("Enter the first number:"); var second = prompt("Enter the second number:"); var sum = Number(first) + Number(second); alert(sum); // Second Code Sample ...

Creating JavaScript objects through function calls

let getBoxWidth = function() { this.width=2; }; alert(getBoxWidth.width); Hello there! Can you explain why the output is undefined in this scenario? ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

Determining the cursor location within a character in a div that is content editable using AngularJS

I am facing challenges with obtaining the cursor caret position within a contenteditable div. Currently, I am utilizing the following function : onBlurArea (field, ev) { ev.preventDefault() const editable = ev.target.childNodes[1].childNodes[2] ...

Tips for launching different web browsers via hyperlinks?

My app has a link that I want mobile users from apps like LinkedIn to open in a browser such as Safari. I attempted this: <a href="safari-https://meed.audiencevideo.com">May open on Safari</a>' However, when I click the link, it opens i ...

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

Utilizing a Single Background Image Across Several Div Elements

Let me illustrate my question using a sequence of images. The div container is set to display the background image as follows: In addition, there will be tile-shaped divs layered on top of the image: I aim to have the background image visible only withi ...

Create a JavaScript variable every few seconds and generate a JSON array of the variable whenever it is updated

My variable, which consists of random numbers generated by mathrandom every second, such as "14323121", needs to be saved to an array for the latest 10 updates. function EveryOneSec() { var numbers = Math.random(); // I want to create an array from th ...

Capture an image from the webcam without any manual intervention and store it in the system's directories

Looking to automate the process of capturing a picture from a webcam once access is granted, and then saving it without any user intervention. I've managed to capture the image but struggling with: A) Automating the capture process B) Saving the ca ...

The shadow effect in three.js differs from that in Unity 3D

When I import a 3D model in .fbx format to my scene using three.js, I noticed that the shadow effect is not as sharp as when using Unity. The shadows appear too blurry. Is there a way to adjust the shadowMap setting in three.js to match the shadow quality ...

What causes the slowness of onsubmit=" " function?

Initially, I had the following setup: HTML: <form onsubmit="return validate()"> ... <input type="submit" id="submit-button"/> </form> JS: function validate() { // Extensive validation process with regex and more... $(& ...

Utilizing document.write to switch up the content on the page

Every time I attempt to utilize document.write, it ends up replacing the current HTML page content. For instance, consider this HTML code: <body> <div> <h1>Hello</h1> </div> and this jQuery code: var notif = document. ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

Why doesn't Mongoose automatically generate an _id for my array elements when I push them in?

I am looking for a way to have mongoose automatically add an _id field to the objects I push into my array. Here is my mongoose schema: var playerModel = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "Users", }, cl ...

Converting JSON data into a JavaScript array and storing it in a variable

Currently, I am delving into the world of JavaScript and my instructor has assigned a task that involves utilizing information from a JSON file within our JavaScript code. The issue I'm facing is deciphering how to effectively convert the JSON data i ...

Using Mongoose schema with a reference to an undefined 'ObjectID' data type

I am currently working on establishing relationships between my schemas, and I have encountered some issues with my solution. Here is how my device schema looks like: var deviceSchema = schema({ name : String, type : String, room: {type: mongo ...

The art of finding information algorithm

Having a JSON file containing about 10,000 records, each record includes a timestamp in the format '2011-04-29'. Currently, I also have a client-side array (referred to as our calendar) with arrays such as - ['2011-04-26', '2011- ...

Creating a Set of Buttons in HTML

Need some assistance with grouped buttons. Let's consider a scenario where there are 5 buttons on an HTML page. When the 3rd button is clicked, buttons from 0 to 3 should change color and the function should return 3. Similarly, when the 5th button is ...