Cease the generation of dynamically produced sounds

I am encountering an issue in Angular where I am unable to stop playing an audio from a service. Below is my play() method:

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

In order to stop all currently playing audios, I created a mute() method within my component:

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

Unfortunately, the console.log does not display any sounds and as a result, none of them are being paused as intended.

Answer №1

document.querySelector('audio') doesn't locate the audio tags because they haven't been inserted into the document.

To insert the audio elements into the document, you can add this line of code at the end of your play() method:

document.querySelector("body").appendChild(audio);

Another option is to store the audio object in an array and pass that array to your component instead of using

document.getElementsByTagName('audio')
. This method is considered better practice than directly manipulating the DOM in Angular applications.

Answer №2

When you write your play function, you are instantiating an Audio object and playing it, however only the browser is aware of this instance...

If you query the DOM, you won't find any reference to your Audio instances... It is crucial to maintain a list of all currently playing audio files, so that you can stop them when needed or mute them.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

Using JavaScript to apply styling on images with overlays

I am currently facing an issue with placing an overlay on top of a background image. Despite my efforts, I am unable to get the background color to appear on top of the image. Any helpful suggestions on how to resolve this would be greatly appreciated. M ...

Guide on releasing a TypeScript component for use as a global, commonJS, or TypeScript module

I have developed a basic component using TypeScript that relies on d3 as a dependency. My goal is to make this component available on npm and adaptable for use as a global script, a commonJS module, or a TypeScript module. The structure of the component is ...

Troubleshooting jQuery compatibility issue in IE6 when using javascript and loading content through ajax

Encountering issues with IE6 and javascript applied to ajax content. Unable to use any type of javascript (plain or with jQuery) on the ajax-retrieved content. The main html page loads the Header content using ajax (specifically utilizing the jQuery ...

Creating a background with image overlays in React: A step-by-step guide

My challenge is to have an image that covers the entire background but it seems to stop abruptly where another object is placed, unable to extend further. I am utilizing Material UI and here is a snippet of my code: import { Image } from "../images&q ...

Unique: "Best Practices for Setting Angular.js Controller Data Directly in the Code"

In this scenario, I need to initialize the data from an inline script, even though I know how to achieve this using a promise on an http request. Currently, the controller is already defined in the header js: var testModule = angular.module('myTestM ...

Is it possible to use mapDispatchToProps in Redux without mapStateToProps?

As I dissect Redux' todo example to gain a deeper understanding, I came across the concept of mapDispatchToProps. This feature allows you to map dispatch actions as props, which led me to consider rewriting addTodo.js by incorporating mapDispatchToPro ...

I am able to see the Redux props showing up in Redux DevTools, but for some reason they are not

I am facing an issue where I am passing a Redux prop to a component that is fetched from a payload. The payload successfully updates the state in my reducer and the component receives the prop (an array of objects fetched in the action) according to my Red ...

Utilizing the Vuex/Redux store pattern to efficiently share a centralized source of data between parent and child components, allowing for customizable variations of the data as

Understanding the advantages of utilizing a store pattern and establishing a single source of truth for data shared across components in an application is essential. Making API calls in a store action that can be called by components, rather than making se ...

Switching the endpoint renders the middleware ineffective

I've encountered a puzzling issue with my NodeJs - Express server, which serves as the backend for my mobile application. The problem arises when I send post requests to certain endpoints like checkmail and checkusername using axios from the frontend ...

Determine the data type of a property by referencing the data type of another property within an array of objects using TypeScript

I am working with a specific type of interface called Route that consists of name and path properties. interface Route { name: string, path: string } const routes = [ { name: "first", path: "/first" }, ...

Form submission issue with dynamically added input fields within a modal

I'm facing a problem where dynamically added input fields in a modal are not being included when the form is submitted. The scenario involves a modal with a form, where input fields are added dynamically upon clicking an "Add" button. Each input fiel ...

Launching an embedded webpage in a separate tab within the main browser window

In my current setup, I have implemented an iframe within the main window. The iframe includes a form where users can input data and submit it. Currently, I achieve the submission with the following code: var openURL = '/results/finalpage'; windo ...

Requesting information from a NodeJs endpoint

I have a NodeJs application that requires calling an end-point (http:\localhost:9900\get\employee - asp.net web-api) to retrieve data. What are some options available for achieving this task? Is it possible to utilize promises in this scenar ...

Angular tutorial on splitting a JSON array

I am looking to extract a portion of a JSON array in Angular. The array looks like the one in the image below.https://i.stack.imgur.com/w0hqC.png Below is the code snippet: export class AppComponent { color: string = 'green'; public stocklis ...

What is the best way to upgrade the "import {Http, Response} from @angular/http" module for Angular 6?

Here is a code snippet that I am working with: import { Injectable } from '@angular/core'; import { Dish } from '../shared/dish'; import { Observable } from 'rxjs'; import { HttpClient, HttpResponse } from '@angular/c ...

What is the reason for VS Code not displaying doc comments from type properties when suggesting descriptions and hover info for TypeScript objects?

The problem is clearly visible in the image below, as it pertains to the popup box in VSCode displaying type information and comments. Although the code works fine in VSCode, TypeScript Playground fails to display the comments properly, so it's best ...

Encountering a TypeError in Angular FormControl Jest test: Circular structure being converted to JSON issue

I encountered an error while running tests using Jest in my Angular project UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' | property &apos ...

Exploring MapQuest API: Unraveling the process of dissecting MapQuest

I am currently exploring MapQuest navigation and utilizing JavaScript code to retrieve the data. Although I am able to extract JSON content in my application, I am unsure of how to utilize this data for navigation. I have started a new project and execute ...

Converting HTML tables into arrays

I have JSON content that needs to be transformed into an array, specifically from a HTML table with cell values. Those cells should be combined into a single array for further use in the project. Struggling with the conversion of cell values into an arra ...