mirror of
https://github.com/motion-canvas/motion-canvas.git
synced 2026-01-12 15:28:03 -05:00
feat: audio playback
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -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[] = [];
|
||||
|
||||
Reference in New Issue
Block a user