'Degraded sound quality after multiple plays with JavaScript Audio Object
My HTML view has many buttons to play various audio files. Each audio file is a few seconds long. The first audio file sounds good but as I click additional buttons the audio quality sounds increasingly degraded. Sometimes it seems like the same audio file is playing twice, one delayed by a few milliseconds. Refreshing the page results in clean sound for the next few clicks.
The Audio() documentation says:
Memory usage and management: If all references to an audio element created using the Audio() constructor are deleted, the element itself won't be removed from memory by the JavaScript runtime's garbage collection mechanism if playback is currently underway. Instead, the audio will keep playing and the object will remain in memory until playback ends or is paused (such as by calling pause()). At that time, the object becomes subject to garbage collection.
I'm thinking that I'm creating a new JavaScript Audio Object every time the user clicks a button and not disposing of the JavaScript Audio Objects after the audio file finishes playing. Here's my code:
this.phonemeFactoryService.getPhoneme().subscribe((phone: any) => { // download phoneme object
this.phonemeObject = phone;
let audio = new Audio(); // JavaScript Audio Object
audio.src = this.phonemeObject.audio; // set audio source
audio.load();
audio.play();
// audio.destroy(); <-- do I need something like this?
});
Do I need to tell it to destroy the JavaScript Audio Object when it finishes playing?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|