Anna F
Anna F

Reputation: 1683

How to mute and unmute sound in Angular2?

I have a sound in my Angular project, like this:

introInfo() {
   this.audio.src = '../assets/sound1.wav';
   this.audio.load();
   this.audio.play();
 }

 feedbackInfo() {
   this.audio.src = '../assets/sound1.wav';
   this.audio.load();
   // auto-start
   this.audio.play();
 }

And I would like to be able to mute all sounds. If I click the button in my template:

<img class="grow" id="mute" [src]='mute' (click)="muteF()"/>

How could I write my function muteF? I would like to mute if I click the button. If I click a second time, it must perform unmute.

Upvotes: 5

Views: 3061

Answers (3)

Volkan Paksoy
Volkan Paksoy

Reputation: 6967

You can use muted property such as

this.audio.muted = true;

Works for video element as well.

Source: https://www.w3schools.com/tags/av_prop_muted.asp

Upvotes: 0

Anna F
Anna F

Reputation: 1683

This works for me

  muteF() {
    if (this.audio.volume !== 0) {
      this.audio.volume = 0;
    } else {
      this.audio.volume = 1;
    }
  }

Upvotes: 2

roberto tom&#225;s
roberto tom&#225;s

Reputation: 4687

something like this probably (unless angular has audio-specific features, for example).

Component

import { ElementRef, Inject, Injectable, ViewChild } from '@angular/core';

@Injectable()
export class MyService {
  @ViewChild('audio') audio: ElementRef

  constructor(/* DOCUMENT would be an option too, from @angular/platform-browser - `@Inject(DOCUMENT) private document: any` */) {}
  introInfo() {
    this.audio.nativeElement.load()
    this.audio.nativeElement.play()
  }
//...
}

then in the template

template

<audio #audio></audio>

Upvotes: 0

Related Questions