How to mute and enable sound in Angular2?

I have a sound in my Angular project, for example:

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 turn off all sounds. If I click the button in the template:

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

How could I write my function muteF? I would like to mute if I press a button. If I click a second time, it should execute unmute.

+4
source share
2 answers

It works for me

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

something like this (e.g. angular has audio-specific functions).

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>
0
source

Source: https://habr.com/ru/post/1683272/


All Articles