4

When user clicks a button, a function plays an audio file. When this file is finished, I need to call another function.

I cannot find a way to bind this event, i've tried adding onended on audio tag, attach a eventlistener through my component, setting player currentTime to 0 and i don't really know if Angular has a () or [] way of biding this state

What is the best/correct approach?

TEMPLATE:

    <div class="telaJogo container-fluid" *ngIf="showJogo">
     <audio id="player">
      <source src="/assets/vaifilhao.mp3" type="audio/mp3">
      Your browser does not support the audio element.  
     </audio>
    <img src="/assets/play.png" alt="play" (click)="play()">

SERVICE:

    /**
    Gera próxima música a ser tocada
  */
  novaRodada(): void {
    console.log('cheguei aqui');
    let player = <HTMLAudioElement>document.getElementById("player");
    player.src = '/assets/Queen - Love of My Life.mp3';
    player.play();
  }

COMPONENT:

/**
    Toca a contagem e gera próxima música
  */
  play(): void {
    this.player.play();
    this.player.currentTime = 0;
  }

  /**
    Gera próxima música a ser tocada
  */
  novaRodada(): void {
    this.jogoService.novaRodada();
  }

3 Answers 3

4

medias like audio and video triggers an event called onended once the media has reach its end. So you can attach a function direct to that event on the controller of your component like this.

Notice the event (ended) on the audio tag element

audio.component.html

<audio (ended)="audioEnded()" preload="auto" #audioPlayer>
    <source [src]="pathToTheSource" type="audio/mp3">
</audio>

audio.component.ts

@ViewChild('audioPlayer') audioPlayer: ElementRef;

audioEnded(): void {
    console.log('ended!!')
}
Sign up to request clarification or add additional context in comments.

Comments

3

Try this way...

    play(): void {
    this.player.play();
    this.player.onended = function() {
        alert("The audio has ended");
     };
  }

Comments

1

Detecting when audio stopped playing:

const player = <HTMLAudioElement>document.getElementById("player");

Observable.fromEvent(player, 'ended').subscribe(console.log);

But it's realy not angular way. You could create directive and attach it to audio tag. Directives may contain @Inputs so you can define what should be do on ended event.

In directive you can use @HostListener('ended')

See more: https://angular.io/guide/attribute-directives#attribute-directives

1 Comment

AudioModel is already declared as HTMLAudioElement. It contains all stuff such as play, paused etc. see: webplatform.github.io/docs/dom/HTMLAudioElement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.