要修复 Angular 中的音频进度条,可以使用“AudioContext”和“AnalyserNode”。在每个刷新周期中,可以将音频数据读取到AnalyserNode中,然后使用此数据更新进度条。以下是示例代码:
在组件中定义以下变量:
audioContext: AudioContext;
analyser: AnalyserNode;
source: MediaElementAudioSourceNode;
requestAnimationFrameId: number;
progressBarWidth: number;
在 ngOnInit() 生命周期钩子中初始化变量:
ngOnInit() {
this.audioContext = new AudioContext();
this.analyser = this.audioContext.createAnalyser();
this.source = this.audioContext.createMediaElementSource(this.audioPlayer.nativeElement);
this.source.connect(this.analyser);
this.analyser.connect(this.audioContext.destination);
this.progressBarWidth = this.progressBar.nativeElement.offsetWidth;
}
在 ngAfterViewInit() 生命周期钩子中设置进度条更新函数:
ngAfterViewInit() {
this.requestAnimationFrameId = requestAnimationFrame(() => this.updateProgressBar());
}
updateProgressBar() {
const bufferLength = this.analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
this.analyser.getByteFrequencyData(dataArray);
const currentPercentage = (this.audioPlayer.nativeElement.currentTime / this.audioPlayer.nativeElement.duration) * 100;
const progressWidth = (currentPercentage / 100) * this.progressBarWidth;
this.progressBar.nativeElement.style.width = `${progressWidth}px`;
this.requestAnimationFrameId = requestAnimationFrame(() => this.updateProgressBar());
}
在 ngOnDestroy() 生命周期钩子中取消 requestAnimationFrame:
ngOnDestroy() {
cancelAnimationFrame(this.requestAnimationFrameId);
}