5

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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Anna F
  • 1,583
  • 4
  • 22
  • 42
  • Did you try setting the volume to 0? something like `this.audio.volume = 0;` – Omri Luzon Aug 08 '17 at 18:38
  • Set `this.audio.muted` to `true` however you like. – isherwood Aug 08 '17 at 18:39
  • @RahulSingh I don't use player yet.. I don't know if I need player just for one function – Anna F Aug 08 '17 at 18:43
  • @AnnaF you are looking for something like [this](http://jsfiddle.net/mattball/sVwXH/), you can make use of viewchild or viewchildren to get the all audio element or elements and then add the muted property to them to true this will solve the problem i guess – Rahul Singh Aug 08 '17 at 18:45

3 Answers3

2

This works for me

  muteF() {
    if (this.audio.volume !== 0) {
      this.audio.volume = 0;
    } else {
      this.audio.volume = 1;
    }
  }
Anna F
  • 1,583
  • 4
  • 22
  • 42
0

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>
roberto tomás
  • 4,435
  • 5
  • 42
  • 71
0

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

Volkan Paksoy
  • 6,727
  • 5
  • 29
  • 40