Jim
Jim

Reputation: 385

Stop dynamically created audios

I'm playing an audio from a service in Angular but I can't manage to make it stop. Here's my play() method:

play(item: string): void {
  const audio = new Audio();
  audio.src = item;
  audio.load();
  audio.play();
}

Then, in my component I created a mute() method where I'd like to stop all audios currently playing:

mute(): void {
  const sounds = document.getElementsByTagName('audio');
  console.log(sounds);
  for (let i = 0; i < sounds.length; i++) {
    sounds[i].pause();
  }
}

However, it doesn't display any sounds in my console.log and, therefore, none of them are being paused.

Upvotes: 2

Views: 206

Answers (2)

gilamran
gilamran

Reputation: 7304

In your play method you created an instance of Audio and let it play, but no one other than the browser know about this instance...

Query the DOM will not result in your Audio instances... You MUST hold a list all of the playing audio file/s. and on mute stop them/it.

Upvotes: 1

Hendrik Brummermann
Hendrik Brummermann

Reputation: 8312

document.getElementsByTagName('audio') does not find the audio-tags because they have not been added to the document.

You can add the audio-elements to the document with this line of code at the end of your play()-method: document.getElementsByTagName("body")[0].appendChild(audio);

Alternatively you can keep the audio object in an array and make that array available to your component instead of using document.getElementsByTagName('audio'). This approach is considered preferable over direct DOM manipulation in Angular applications.

Upvotes: 1

Related Questions