7

I have a component which play an mp3 file, and it gets the played file name from its parent. Here is the code:

export class PlayComponent implements OnChanges  {

      @Input() fileToPlay:string;

      ngOnChanges(arg){

         console.log(arg.fileToPlay);
      }
    }

and the html is:

<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 fine for first play. The value of fileToPlay may change and i want to play the new file on real time, but it always play the first file name.

How can i fix it?

Sal-laS
  • 11,016
  • 25
  • 99
  • 169

3 Answers3

12

I know this is old but I had the same problem and the only thing that worked for me was putting the src in the audio not the source:

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

couldn't find anything on google so figured it out myself, hope it helps someone

Jan V.
  • 180
  • 3
  • 12
4

Try to check by changing your Component and HTML as 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>
ranakrunal9
  • 13,320
  • 3
  • 42
  • 43
  • 1
    No, i am not checking for change every second. What i am doing is, when any change happen i will check `fileToPlay` variables `previous` and `current` value if both are different and not empty then i am setting `showPlayer` to `false` which will hide your player and after `0` millisecond of time out i am setting `showPlayer` to `true` which will display player again. Here timeout is `0` which will display player and recreates it in a blink of an eye. – ranakrunal9 Dec 24 '16 at 11:39
0

Instead of using the HTML Element, you can use directly javascript to manipulate audio. See this post : How to play mp3 with Angular 2?

Community
  • 1
  • 1
l.cotonea
  • 2,037
  • 1
  • 15
  • 17