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.