Skip to content

🎥 Make videos programmatically with React

audio sync time

JonnyBurgerea35ddac3aa1
diff --git a/packages/media/src/debug-overlay/preview-overlay.ts b/packages/media/src/debug-overlay/preview-overlay.ts
index 4442913e96..b4c263e86c 100644
--- a/packages/media/src/debug-overlay/preview-overlay.ts
+++ b/packages/media/src/debug-overlay/preview-overlay.ts
@@ -6,10 +6,12 @@ export type DebugStats = {
export const drawPreviewOverlay = (
context: CanvasRenderingContext2D,
stats: DebugStats,
+ audioContextState: AudioContextState,
+ audioSyncAnchor: number,
) => {
// Optionally, set a background for text legibility
context.fillStyle = 'rgba(0, 0, 0, 1)';
- context.fillRect(20, 20, 300, 100);
+ context.fillRect(20, 20, 600, 180);
context.fillStyle = 'white';
context.font = '24px sans-serif';
@@ -21,4 +23,6 @@ export const drawPreviewOverlay = (
60,
);
context.fillText(`Frames rendered: ${stats.framesRendered}`, 30, 90);
+ context.fillText(`Audio context state: ${audioContextState}`, 30, 120);
+ context.fillText(`Audio time: ${audioSyncAnchor.toFixed(3)}s`, 30, 150);
};
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.ts
index f848e7d0e8..69be71885c 100644
--- a/packages/media/src/media-player.ts
+++ b/packages/media/src/media-player.ts
@@ -86,7 +86,7 @@ export class MediaPlayer {
private initializationPromise: Promise<MediaPlayerInitResult> | null = null;
- private bufferState: ReturnType<typeof useBufferState> | null = null;
+ private bufferState: ReturnType<typeof useBufferState>;
constructor({
canvas,
@@ -322,6 +322,7 @@ export class MediaPlayer {
this.currentSeekNonce++;
const nonce = this.currentSeekNonce;
await this.seekPromiseChain;
+ await this.renderPromiseChain;
this.seekPromiseChain = this.seekToDoNotCallDirectly(time, nonce);
await this.seekPromiseChain;
@@ -599,15 +600,14 @@ export class MediaPlayer {
// Frame is not immediately available, so we are buffering
// until it is
- // TODO: Race conditions with shared audio context
- this.sharedAudioContext.suspend();
const delayHandle = this.bufferState?.delayPlayback();
const frame = (await nextFrame.waitPromise()) ?? null;
delayHandle?.unblock();
- this.sharedAudioContext.resume();
-
if (!this.videoFrameIterator.isDestroyed() && frame) {
+ this.audioSyncAnchor =
+ this.sharedAudioContext.currentTime - frame.timestamp;
+
this.drawFrame(frame);
}
}
@@ -666,7 +666,12 @@ export class MediaPlayer {
private drawDebugOverlay(): void {
if (!this.debugOverlay) return;
if (this.context && this.canvas) {
- drawPreviewOverlay(this.context, this.debugStats);
+ drawPreviewOverlay(
+ this.context,
+ this.debugStats,
+ this.sharedAudioContext.state,
+ this.sharedAudioContext.currentTime,
+ );
}
}