feat: audio playback

This commit is contained in:
aarthificial
2022-02-20 01:12:28 +01:00
parent 9a0c3657c4
commit e9a6fdb51e
2 changed files with 30 additions and 3 deletions

View File

@@ -1,14 +1,35 @@
import {Project} from './Project';
const MINIMUM_ANIMATION_DURATION = 1000;
const MAX_AUDIO_DESYNC = 1 / 50;
export function Player(factory: () => Project) {
export function Player(factory: () => Project, audioSrc?: string) {
const project = factory();
let startTime = performance.now();
let audio: HTMLAudioElement;
if (audioSrc) {
audio = new Audio(audioSrc);
audio.play();
}
project.start();
const run = () => {
if (audio?.currentTime < project.time) {
requestAnimationFrame(run);
return;
}
try {
if (project.next()) {
let finished = project.next();
// Synchronize animation with audio.
if (audio?.currentTime - MAX_AUDIO_DESYNC > project.time) {
while (audio.currentTime > project.time && !finished) {
finished = project.next();
}
}
if (finished) {
// Prevent animation from restarting too quickly.
const animationDuration = performance.now() - startTime;
if (animationDuration < MINIMUM_ANIMATION_DURATION) {
@@ -16,10 +37,13 @@ export function Player(factory: () => Project) {
return;
}
startTime = performance.now();
project.start();
project.next();
if (audio) {
audio.currentTime = 0;
}
}
requestAnimationFrame(run);
} catch (e) {
console.error(e);

View File

@@ -30,6 +30,9 @@ export class Project extends Stage {
public readonly center: Vector2d;
public framesPerSeconds = 60;
public frame: number = 0;
public get time(): number {
return this.framesToSeconds(this.frame);
}
private runner: Generator;
private scenes: Scene[] = [];