Skip to content

Visualize Your Ideas With Code

feat(core): hot module replacement for audio (#793)

Jacobd40c1a83c645
diff --git a/packages/core/src/media/AudioManager.ts b/packages/core/src/media/AudioManager.ts
index a9a5b512..46f597a3 100644
--- a/packages/core/src/media/AudioManager.ts
+++ b/packages/core/src/media/AudioManager.ts
@@ -25,7 +25,6 @@ export class AudioManager {
});
}
}
-
public getTime() {
return this.toAbsoluteTime(this.audioElement.currentTime);
}
@@ -107,7 +106,12 @@ export class AudioManager {
const response = await fetch(this.source, {signal});
const rawBuffer = await response.arrayBuffer();
if (signal.aborted) return;
- const audioBuffer = await this.decodeAudioData(rawBuffer);
+ let audioBuffer: AudioBuffer;
+ try {
+ audioBuffer = await this.decodeAudioData(rawBuffer);
+ } catch (e) {
+ return;
+ }
if (signal.aborted) return;
const sampleSize = 256;
@@ -164,7 +168,7 @@ export class AudioManager {
private decodeAudioData(buffer: ArrayBuffer): Promise<AudioBuffer> {
return new Promise<AudioBuffer>((resolve, reject) =>
- this.context.decodeAudioData(buffer, resolve, reject),
+ this.context.decodeAudioData(buffer, resolve, reject).catch(reject),
);
}
}
diff --git a/packages/vite-plugin/src/main.ts b/packages/vite-plugin/src/main.ts
index 5a9e1b08..0e2725eb 100644
--- a/packages/vite-plugin/src/main.ts
+++ b/packages/vite-plugin/src/main.ts
@@ -13,6 +13,8 @@ import {PluginOptions, isPlugin, PLUGIN_OPTIONS, ProjectData} from './plugins';
import {openInExplorer} from './openInExplorer';
import * as os from 'os';
+const AudioExtensions = new Set(['.mp3', '.wav', '.ogg', '.aac', '.flac']);
+
export interface MotionCanvasPluginConfig {
/**
* The import path of the project file or an array of paths.
@@ -53,7 +55,7 @@ export interface MotionCanvasPluginConfig {
* there. This leaves the original files open for modification with hot module
* replacement still working.
*
- * @defaultValue /\.(wav|ogg)$/
+ * @defaultValue /^$/
*/
bufferedAssets?: RegExp | false;
/**
@@ -90,7 +92,7 @@ export interface MotionCanvasPluginConfig {
export default ({
project = './src/project.ts',
output = './output',
- bufferedAssets = /\.(wav|ogg)$/,
+ bufferedAssets = /^$/,
editor = '@motion-canvas/ui',
proxy,
}: MotionCanvasPluginConfig = {}): Plugin => {
@@ -331,6 +333,15 @@ export default ({
`export default meta;`,
);
}
+
+ if (AudioExtensions.has(ext)) {
+ return source(
+ code,
+ `if (import.meta.hot) {`,
+ ` import.meta.hot.accept();`,
+ `}`,
+ );
+ }
},
handleHotUpdate(ctx) {
const now = Date.now();