SimplySpoons
SimplySpoons

Reputation: 113

Play sound on button click (Angular)

I'm trying to play a sound when a link is clicked

This is what I have, however, it doesn't work and seems to slow the browser down significantly whenever I have it added into the files

HTML:

<a routerLinkActive="active" routerLink="/tomato2" class="tomato" (click)="playAudio()">
  <img class="tomato_1" src="https://freepngimage.com/content/uploads/images/tomato-7866.png" />
</a>

TS:

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'home',
  templateUrl: './catalog.component.html'
})

export class CatalogViewComponent {
    playAudio(){
      let audio = new Audio();
      audio.src = "http://www.schillmania.com/projects/soundmanager2/demo/mpc/audio/CHINA_1.mp3";
      audio.load();
      audio.play();
      this.playAudio();
    }
}

Upvotes: 2

Views: 6922

Answers (1)

Hassan Ali
Hassan Ali

Reputation: 1029

If you are using angular 2+ this will helpful.

<audio #ref src="https://soundbible.com/grab.php?id=1964&type=mp3"></audio>

<button (click)="ref.play()">▶️ play</button>
<button (click)="ref.pause()">⏸ pause</button>

StackBiltz

Upvotes: 3

Related Questions