Visualize Your Ideas With Code
feat: audio playback
aarthificiale9a6fdb51e62
diff --git a/src/Player.ts b/src/Player.tsindex 9dc1a6b0..f7b23d36 100644--- a/src/Player.ts+++ b/src/Player.ts@@ -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);diff --git a/src/Project.ts b/src/Project.tsindex 611f5262..834139ff 100644--- a/src/Project.ts+++ b/src/Project.ts@@ -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[] = [];