英文:
Angular animation with plugged sounds/audio when animation trigger is being called
问题
我正在寻找一个解决方案,每次调用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();
}
}
英文:
I am looking for a solution to play audio each time the Angular animation trigger is called. I have an animation with 8 elements (8 triggers) with different duration and delays.
I was trying to implement audio.play() method each time animation has started but it's not working properly at all.
(@trigger.start)="playAudio($event)"
playAudio(event: any) {
if (event['fromState'] !== 'void') {
let audio = new Audio('../../assets/audio/click1.wav');
audio.play();
}
}
Thank you for any help!
答案1
得分: 2
我认为你不应该每次调用该函数时都创建一个新的音频对象。这可能会导致不一致,特别是如果你快速连续调用它。你可以预加载音频,只在需要时播放:
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>
英文:
I think you shouldn't create a new Audio Object, everytime you call the function. This can lead to inconsistency as you said, especially if u call it in quick succession. You can preload the audio and just play it when needed:
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();
}
}
}
Your binding in the html/template stays the same:
<div [@trigger.start]="playAudio($event)"></div>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论