'Playing HTML sounds repeatedly on mobile has weird behavior
I have a js program that makes sounds play repeatedly via a timer and works perfectly fine on my computer, however, it does not work when I try to use it on my phone(iPhone 13) or tablet(iPad air 4). The sound is either late or does not play at all. If it provides any clues, I've also noticed that if I change the phone's system volume(with the physical buttons on the side of the phone) while the program is running, the volume bar lags and jumps instead of smoothly increasing or decreasing.
Setup to allow sounds to play on ios(since they need user interaction)
var click1 = new Audio('../audio/click1.mp3');
click1.preload = "auto";
enterBtn.addEventListener('click', () => {
//...code
click1.volume = 0;
click1.play();
click1.pause();
click1.currentTime = 0;
click1.volume = 1;
});
The code that runs when it is called by a timer
function playClick() {
click1.load();
click1.play();
click1.currentTime = 0;
//...code
}
Timer code that I took from stack overflow
function Timer(callback, timeInterval, options) {
this.timeInterval = timeInterval;
this.start = () => {
this.expected = Date.now() + this.timeInterval;
this.theTimeout = null;
if (options.immediate) {
callback();
}
this.timeout = setTimeout(this.round, this.timeInterval);
console.log('Timer Started');
}
this.stop = () => {
clearTimeout(this.timeout);
}
this.round = () => {
var drift = Date.now() - this.expected;
if (drift > this.timeInterval) {
if (options.errorCallback) {
options.errorCallback();
}
}
callback();
this.expected += this.timeInterval;
this.timeout = setTimeout(this.round, Math.max(0,this.timeInterval - drift));
}
}
export default Timer;
Solution 1:[1]
What about using setInterval instead of a Timer?
https://developer.mozilla.org/en-US/docs/Web/API/setInterval
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rajniszp |
