Commit c819ed15 authored by 王猛's avatar 王猛

fix: 修复题目模板快速切页后音频无声

parent 1a3decc3
......@@ -23,6 +23,7 @@ import TWEEN from '@tweenjs/tween.js';
import {BehaviorSubject} from 'rxjs';
import { animate, keyframes, state, style, transition, trigger } from '@angular/animations';
import { NzModalService } from 'ng-zorro-antd';
import { TemplateAudioOutput } from './template-audio-output';
......@@ -95,14 +96,15 @@ import { NzModalService } from 'ng-zorro-antd';
})
export class PlayComponent implements OnInit, OnDestroy {
saveKey = 'ww_question2';
questionAudio = new Audio();
private audioOutput = new TemplateAudioOutput(4);
questionAudio = this.audioOutput.audios[0];
playerState = new BehaviorSubject<any>({ isPlaying: false });
options;
zoomIn;
rightAudio = new Audio();
wrongAudio = new Audio();
rightAudio = this.audioOutput.audios[1];
wrongAudio = this.audioOutput.audios[2];
OPTION_TYPE = {TEXT: 1, PIC: 2, AUDIO: 3};
optionAudio = new Audio();
optionAudio = this.audioOutput.audios[3];
// 数据
data;
......@@ -192,14 +194,19 @@ export class PlayComponent implements OnInit, OnDestroy {
}, 1);
}
ngOnDestroy() {
this.rightAudio.pause();
this.wrongAudio.pause();
this.optionAudio.pause();
this.audioOutput.dispose();
this.rightAudio = null;
this.wrongAudio = null;
this.optionAudio = null;
}
@HostListener('window:pagehide', ['$event'])
onPageHide(event: PageTransitionEvent) {
if (!event.persisted) {
this.audioOutput.dispose();
}
}
transCharCode(index) {
return String.fromCharCode(65 + index);
}
......@@ -207,10 +214,10 @@ export class PlayComponent implements OnInit, OnDestroy {
handleAnimation(item) {
if (item.right) {
item.state = 'right';
this.rightAudio.play();
this.audioOutput.play(this.rightAudio);
} else {
item.state = 'wrong';
this.wrongAudio.play();
this.audioOutput.play(this.wrongAudio);
setTimeout(() => {
item.state = '';
}, 1500);
......@@ -232,7 +239,7 @@ export class PlayComponent implements OnInit, OnDestroy {
e.stopPropagation();
this.optionAudio.src = option.audio_id;
// this.optionAudio.load();
this.optionAudio.play();
this.audioOutput.play(this.optionAudio);
this.changeDetectorRef.markForCheck();
this.changeDetectorRef.detectChanges();
this.refresh();
......@@ -247,9 +254,9 @@ export class PlayComponent implements OnInit, OnDestroy {
playQuestionAudio(e) {
e.stopPropagation();
if (this.questionAudio.paused) {
this.questionAudio.play();
this.audioOutput.play(this.questionAudio);
} else {
this.questionAudio.pause();
this.audioOutput.pause(this.questionAudio);
}
this.changeDetectorRef.markForCheck();
this.changeDetectorRef.detectChanges();
......
/** Keeps this template's audio out of the native output mixer shared by iframes. */
export class TemplateAudioOutput {
readonly audios: HTMLAudioElement[];
private context: AudioContext = null;
private sources: MediaElementAudioSourceNode[] = [];
private disposed = false;
private playRequests = new WeakMap<HTMLAudioElement, object>();
constructor(count: number) {
this.audios = this.createAudios(count);
const Context = window.AudioContext || (window as any).webkitAudioContext;
if (!Context) {
return;
}
let context: AudioContext;
try {
context = new Context();
this.audios.forEach(audio => {
// Set before assigning src: CDN audio must remain readable by Web Audio.
audio.crossOrigin = 'anonymous';
const source = context.createMediaElementSource(audio);
this.sources.push(source);
source.connect(context.destination);
});
this.context = context;
} catch (_) {
this.sources.forEach(source => source.disconnect());
this.sources = [];
this.closeContext(context);
// An element already attached to a source cannot return to native output.
// Fresh elements preserve native playback if Web Audio setup is unsupported.
this.audios = this.createAudios(count);
}
}
play(audio: HTMLAudioElement): void {
if (this.disposed) {
return;
}
const request = {};
this.playRequests.set(audio, request);
let resumed: Promise<void>;
try {
// Both calls must happen in the original click task, without awaiting resume.
resumed = this.context && this.context.state !== 'running' ? this.context.resume() : undefined;
const played = audio.play();
Promise.all([resumed, played]).catch(() => this.cancelFailedPlay(audio, request));
} catch (_) {
Promise.resolve(resumed).catch(() => undefined);
this.cancelFailedPlay(audio, request);
}
}
pause(audio: HTMLAudioElement): void {
this.playRequests.delete(audio);
audio.pause();
}
dispose(): void {
if (this.disposed) {
return;
}
this.disposed = true;
this.audios.forEach(audio => {
this.pause(audio);
audio.removeAttribute('src');
audio.load();
});
this.sources.forEach(source => source.disconnect());
this.sources = [];
this.closeContext(this.context);
this.context = null;
}
private createAudios(count: number): HTMLAudioElement[] {
return Array.from({ length: count }, () => new Audio());
}
private cancelFailedPlay(audio: HTMLAudioElement, request: object): void {
if (!this.disposed && this.playRequests.get(audio) === request) {
this.pause(audio);
}
}
private closeContext(context: AudioContext): void {
if (context && context.state !== 'closed') {
try {
Promise.resolve(context.close()).catch(() => undefined);
} catch (_) {
// The browser may already be closing the context during iframe teardown.
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment