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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With