Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 audio won't break by changing component

I want to play audio with help of this code and it works fine

  ngOnInit () {
    const a = new Audio();
    a.src = '../../assets/hello.wav';
    a.load();
    // auto-start
    a.play();
  }

But when I click Next Button, that leads me to next page ( so I change my component with help of routing) the audio will not stop (will not break) and the music from audio plays on the next page also. What should I add to my code to make it possible by changing page break the audio?

like image 859
Anna F Avatar asked Aug 15 '26 14:08

Anna F


1 Answers

you shall define audio as a field of your component(in order to access it at ngOnDestroy) and destroy it at ngOnDestroy.

audio: any;

ngOnInit () {
  this.audio = new Audio();
  this.audio.src = '../../assets/hello.wav';
  this.audio.load();
  // auto-start
  this.audio.play();
}

ngOnDestroy() {
  // destroy audio here
  if(this.audio) {
    this.audio.pause();
    this.audio = null;
  }
}
like image 60
Pengyy Avatar answered Aug 17 '26 21:08

Pengyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!