调用动画触发器时插入声音/音频的角度动画

问题描述 投票:0回答:1

我正在寻找一种在每次调用 Angular 动画触发器时播放音频的解决方案。我有一个包含 8 个元素(8 个触发器)的动画,具有不同的持续时间和延迟。

我试图在每次动画开始时实现audio.play()方法,但它根本无法正常工作。

(@trigger.start)="playAudio($event)"

    playAudio(event: any) {
    if (event['fromState'] !== 'void') {
        let audio = new Audio('../../assets/audio/click1.wav');
        audio.play();
    }
}

感谢您的帮助!

angular typescript angular-animations
1个回答
0
投票

我认为你不应该在每次调用该函数时创建一个新的音频对象。正如您所说,这可能会导致不一致,特别是如果您快速连续调用它。您可以预加载音频并在需要时播放:

import { Component } from '@angular/core';
import { trigger, transition, style, animate } from '@angular/animations';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css'],
  animations: [
    trigger('trigger', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('1s', style({ opacity: 1 })),
      ]),
    ]),
  ],
})
export class YourComponent {
  private audio: HTMLAudioElement;

  constructor() {
    this.audio = new Audio('../../assets/audio/click1.wav');
  }

  playAudio(event: any) {
    if (event['fromState'] !== 'void') {
      this.audio.play();
    }
  }
}

您在 html/模板中的绑定保持不变:

<div [@trigger.start]="playAudio($event)"></div>
© www.soinside.com 2019 - 2024. All rights reserved.