Reputation: 509
I want to create a simple function that plays a specific sound file based on the argument you pass to it. I understand that I need to use something like this:
const audio = new Audio("freejazz.wav");
audio.play()
But what would you do if you had 3 different sound files? A, I supposed to have const audio1 = new Audio("paidjazz.wave");
etc?
I will be calling these files regularly, so will the 'new' keyword keep calling fresh instances, leading to a memory leak?
How can I create a function that plays the sound if I use something like play("MySoundName")
?
Upvotes: 2
Views: 55
Reputation: 419
According to this page on MDN the documentation seems to suggest that the construction of a new Audio
object sets up a "wrapper" (not sure if that's quite the term I'm after here, but I'll stick with it for now) around an audio file with methods you can call etc.
The new
keyword will create fresh instances, yes. So you should probably do outside of wherever the audio is being played from so that it only happens once.
i.e:
The following will play pop 100 times, but unless you put new Audio()
inside the loop I would not expect it to keep creating new instances
const pop =new Audio('pop.mp3');
for(let i=0; i<=100; i++) {
// play pop
}
Upvotes: 1