Home > Back-end >  Angular 12 - Pass index number for custom audio player
Angular 12 - Pass index number for custom audio player

Time:11-26

Hello i created an audio slide show for my ionic 5 Angular 12 project.

The audio player is custom made, NOT the default HTML5 audio player as you will see in the html code

The Audio sound plays ok as it should for each audio file.

My problem is that the pause icon shows in all audios if you press one audio to play.

Let me show you code so that you 'll understand

.html

<ion-slide *ngFor="let media of medias | filterByType: mediaType; let i = index">
    <ng-container>
       <ion-segment color="light">
          <ion-segment-button layout="icon-bottom" color="light"
          *ngIf="!displayPlay[i]" 
             (click)="playAudio(media?.image_path,i)">
            <ion-icon name="play" color="light"></ion-icon>
            <ion-label>Play</ion-label>
            </ion-segment-button>
        <ion-segment-button layout="icon-bottom" 
         *ngIf="displayPlay[i]" (click)="toggleAudio(i)">
            <ion-icon name="pause" color="light"></ion-icon>
            <ion-label>Pause</ion-label>
        </ion-segment-button>
    </ion-segment>
  </ng-container>
 </ion-slide>

.ts

 displayPlay: any;



playAudio(file: string, index: number) {
    this.audio = new Audio();
    this.audio.src = file;
    this.audio.load();
    this.audio.play();
    this.displayPlay[index] = true;
}

toggleAudio(index) {
    if (this.displayPlay[index]) {
        this.audio.pause();
        this.displayPlay[index] = false;
    }
}

What am I doing wrong? The Play or Pause icon are not being shown. i am getting

core.mjs:6469 ERROR TypeError: Cannot read properties of undefined (reading '0')

enter image description here

CodePudding user response:

You have one displayPlay bookean variable for all of your slides that shows whether they need to show pause or play, this behaviour is the result of that. if you want each slide to decide for itself that it's playing or paused, you need an array of boolean variables. like this: *ngIf="displayPlay[i]" and

playAudio(file: string, index: number) {
    ...
    this.displayPlay[index] = true;
}

toggleAudio(index: number) {
    if (this.displayPlay[index]) {
        this.audio.pause();
        this.displayPlay[index] = false;
    }
}

You can also implement it inside your medias array too. also you won't want to play two files simultaneously so you should make sure to pause all other videos when one of them is played.

Another approach (which is better) is you save the index of the video that is playing in a number variable instead of this whole displayPlay array. whenever an audio is played you change that variable to the index of the playing file. and the show play button condition would be like *ngIf="playingVideoIndex === i"

  • Related