Angular2: restart the html audio tag in real time

I have a component that plays an mp3 file, and it gets the name of the playback file from its parent. Here is the code:

export class PlayComponent implements OnChanges  {

      @Input() fileToPlay:string;

      ngOnChanges(arg){

         console.log(arg.fileToPlay);
      }
    }

and html:

<div *ngIf="fileToPlay!=''">
    <audio  controls autoplay class="playa" di="audio">
      <source [src]="fileToPlay" type="audio/mpeg">
      Your browser does not support the audio element.
    </audio>
</div>

It works great for the first game. The value fileToPlaycan be changed, and I want to play a new file in real-time, but he always plays the first file name.

How can i fix this?

+4
source share
3 answers

Try checking by changing the component and HTML as shown below:

// your component

import { Component, Input, OnChanges, SimpleChange } from '@angular/core';

export class PlayComponent implements OnChanges  {

  private showPlayer: boolean = false; 
  @Input() fileToPlay:string;

  ngOnInit(){
    if (this.fileToPlay != '') {
      this.showPlayer = true;
    }
  }

  ngOnChanges(changes: {[propKey: string]: SimpleChange}){

     if(changes['fileToPlay'].previousValue !== changes['fileToPlay'].currentValue && changes['fileToPlay'].currentValue !== '') {
      this.showPlayer = false;
      setTimeout(() => this.showPlayer = true, 0);
    }
  }
}

// HTML

<div *ngIf="showPlayer">
  <audio  controls autoplay class="playa" di="audio">
    <source [src]="fileToPlay" type="audio/mpeg">
    Your browser does not support the audio element.
  </audio>
</div>
+3
source

, , , , , , src :

<audio controls src={{filetoplay}}></audio>

- Google, , , -

+3

Instead of using an HTML element, you can use javascript directly to control the audio. Watch this post: How to play mp3 using Angular 2?

0
source

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


All Articles