Skip to content

🎥 Make videos programmatically with React

Add SFX drag support for Studio

Cursor Agentfb4806599237
diff --git a/packages/docs/components/sfx-demos/sfx-drag-data.ts b/packages/docs/components/sfx-demos/sfx-drag-data.ts
new file mode 100644
index 0000000000..1aa60f5853
--- /dev/null
+++ b/packages/docs/components/sfx-demos/sfx-drag-data.ts
@@ -0,0 +1,46 @@
+import {SFX_DRAG_MIME_TYPE, type SfxDragData} from '@remotion/studio-shared';
+
+export const makeSfxDragData = ({
+ name,
+ url,
+}: {
+ readonly name: string;
+ readonly url: string;
+}): SfxDragData => {
+ return {
+ type: 'remotion-sfx',
+ version: 1,
+ sfx: {
+ name,
+ url,
+ },
+ };
+};
+
+export const getSfxNameFromUrl = (src: string): string => {
+ try {
+ const url = new URL(src);
+ return (
+ url.pathname
+ .split('/')
+ .pop()
+ ?.replace(/\.[^.]+$/, '') || 'SFX'
+ );
+ } catch {
+ return 'SFX';
+ }
+};
+
+export const setSfxDragData = ({
+ dataTransfer,
+ dragData,
+}: {
+ readonly dataTransfer: DataTransfer;
+ readonly dragData: SfxDragData;
+}) => {
+ const serialized = JSON.stringify(dragData);
+ dataTransfer.effectAllowed = 'copy';
+ dataTransfer.setData(SFX_DRAG_MIME_TYPE, serialized);
+ dataTransfer.setData('application/json', serialized);
+ dataTransfer.setData('text/plain', serialized);
+};
diff --git a/packages/docs/docs/sfx/PlayButton.tsx b/packages/docs/docs/sfx/PlayButton.tsx
index d23bb8eba7..a35ee0cf42 100644
--- a/packages/docs/docs/sfx/PlayButton.tsx
+++ b/packages/docs/docs/sfx/PlayButton.tsx
@@ -1,5 +1,10 @@
import {Button} from '@remotion/design';
import React, {useCallback, useRef, useState} from 'react';
+import {
+ getSfxNameFromUrl,
+ makeSfxDragData,
+ setSfxDragData,
+} from '../../components/sfx-demos/sfx-drag-data';
export const PlayButton: React.FC<{
readonly src: string;
@@ -8,6 +13,7 @@ export const PlayButton: React.FC<{
}> = ({src, size = 48, depth}) => {
const [playing, setPlaying] = useState(false);
const audioRef = useRef<HTMLAudioElement | null>(null);
+ const sfxName = getSfxNameFromUrl(src);
const iconSize = Math.round(size * 0.5);
@@ -34,8 +40,26 @@ export const PlayButton: React.FC<{
[playing, src],
);
+ const onDragStart = useCallback(
+ (e: React.DragEvent<HTMLDivElement>) => {
+ setSfxDragData({
+ dataTransfer: e.dataTransfer,
+ dragData: makeSfxDragData({
+ name: sfxName,
+ url: src,
+ }),
+ });
+ },
+ [sfxName, src],
+ );
+
return (
- <div style={{width: size, height: size}}>
+ <div
+ style={{width: size, height: size}}
+ draggable
+ onDragStart={onDragStart}
+ title="Drag this sound effect into Remotion Studio"
+ >
<Button
className={`rounded-full p-0`}
style={{width: size, height: size}}
diff --git a/packages/docs/docs/sfx/table-of-contents.tsx b/packages/docs/docs/sfx/table-of-contents.tsx
index 3b2c8d7405..19abfec2d3 100644
--- a/packages/docs/docs/sfx/table-of-contents.tsx
+++ b/packages/docs/docs/sfx/table-of-contents.tsx
@@ -1,4 +1,8 @@
import React from 'react';
+import {
+ makeSfxDragData,
+ setSfxDragData,
+} from '../../components/sfx-demos/sfx-drag-data';
import {Grid} from '../../components/TableOfContents/Grid';
import {TOCItem} from '../../components/TableOfContents/TOCItem';
import {PlayButton} from './PlayButton';
@@ -9,8 +13,20 @@ const SfxItem: React.FC<{
readonly name: string;
readonly description: string;
}> = ({link, src, name, description}) => {
+ const dragData = makeSfxDragData({name, url: src});
+
return (
- <TOCItem link={link}>
+ <TOCItem
+ link={link}
+ draggable
+ onDragStart={(e) => {
+ setSfxDragData({
+ dataTransfer: e.dataTransfer,
+ dragData,
+ });
+ }}
+ title="Drag this sound effect into Remotion Studio"
+ >
<div
style={{
display: 'flex',
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index 2ff17a6144..2bb947135a 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -13,7 +13,10 @@ import type {
JSXElement,
VariableDeclaration,
} from '@babel/types';
-import type {InsertableCompositionElement} from '@remotion/studio-shared';
+import {
+ isRemotionSfxUrl,
+ type InsertableCompositionElement,
+} from '@remotion/studio-shared';
import type {namedTypes} from 'ast-types';
import * as recast from 'recast';
import {formatFileContent} from '../codemods/format-file-content';
@@ -765,6 +768,13 @@ const createStaticFileSrcAttribute = ({
);
};
+const createStringSrcAttribute = (src: string): namedTypes.JSXAttribute => {
+ return recast.types.builders.jsxAttribute(
+ recast.types.builders.jsxIdentifier('src'),
+ recast.types.builders.stringLiteral(src),
+ );
+};
+
const createSolidElement = ({
localName,
width,
@@ -796,7 +806,7 @@ const createAssetElement = ({
dimensions,
}: {
localName: string;
- staticFileLocalName: string;
+ staticFileLocalName: string | null;
src: string;
dimensions: {width: number; height: number} | null;
}): namedTypes.JSXElement => {
@@ -804,7 +814,9 @@ const createAssetElement = ({
recast.types.builders.jsxOpeningElement(
recast.types.builders.jsxIdentifier(localName),
[
- createStaticFileSrcAttribute({staticFileLocalName, src}),
+ staticFileLocalName === null
+ ? createStringSrcAttribute(src)
+ : createStaticFileSrcAttribute({staticFileLocalName, src}),
createPositionAbsoluteStyleAttribute(),
...(dimensions
? [
@@ -1442,7 +1454,15 @@ const createInsertableJsxElement = ({
}
if (element.type === 'asset') {
- const staticFileLocalName = ensureStaticFileImport(ast);
+ if (
+ element.srcType === 'remote' &&
+ (element.assetType !== 'audio' || !isRemotionSfxUrl(element.src))
+ ) {
+ throw new Error('Only @remotion/sfx audio URLs can be inserted remotely');
+ }
+
+ const staticFileLocalName =
+ element.srcType === 'remote' ? null : ensureStaticFileImport(ast);
let localName: string;
if (element.assetType === 'image') {
localName = ensureImgImport(ast);
diff --git a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
index f033f5c18c..8203007065 100644
--- a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
@@ -1,8 +1,9 @@
import {RenderInternals} from '@remotion/renderer';
-import type {
- InsertJsxElementRequest,
- InsertJsxElementResponse,
- InsertableCompositionElement,
+import {
+ isRemotionSfxUrl,
+ type InsertJsxElementRequest,
+ type InsertJsxElementResponse,
+ type InsertableCompositionElement,
} from '@remotion/studio-shared';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {insertJsxElementIntoComposition} from '../../helpers/resolve-composition-component';
@@ -30,7 +31,13 @@ const validateElement = (element: InsertableCompositionElement) => {
}
if (element.type === 'asset') {
- if (!element.src || element.src.includes('\\')) {
+ if (element.srcType === 'remote') {
+ if (element.assetType !== 'audio' || !isRemotionSfxUrl(element.src)) {
+ throw new Error(
+ 'Only @remotion/sfx audio URLs can be inserted remotely',
+ );
+ }
+ } else if (!element.src || element.src.includes('\\')) {
throw new Error('Asset path must be a static file path');
}
diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.ts
index d2d9fe8845..7ecfbb1cc5 100644
--- a/packages/studio-server/src/test/resolve-composition-component.test.ts
+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts
@@ -865,6 +865,57 @@ test('inserts an Audio asset into the resolved composition component', async ()
}
});
+test('inserts a remote SFX audio asset with a literal URL', async () => {
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));
+ try {
+ await fs.writeFile(
+ path.join(tempDir, 'Root.tsx'),
+ [
+ "import {Composition} from 'remotion';",
+ "import {MyComp} from './MyComp';",
+ 'export const RemotionRoot = () => {',
+ '\treturn <Composition id="test" component={MyComp} />;',
+ '};',
+ '',
+ ].join('\n'),
+ );
+ await fs.writeFile(
+ path.join(tempDir, 'MyComp.tsx'),
+ [
+ "import {AbsoluteFill} from 'remotion';",
+ '',
+ 'export const MyComp: React.FC = () => {',
+ '\treturn <AbsoluteFill>hello</AbsoluteFill>;',
+ '};',
+ '',
+ ].join('\n'),
+ );
+
+ const result = await insertJsxElementIntoComposition({
+ remotionRoot: tempDir,
+ compositionFile: 'Root.tsx',
+ compositionId: 'test',
+ element: {
+ type: 'asset',
+ assetType: 'audio',
+ src: 'https://remotion.media/whip.wav',
+ srcType: 'remote',
+ dimensions: null,
+ },
+ prettierConfigOverride: {singleQuote: true, useTabs: true},
+ });
+
+ expect(result.output).toContain("import { Audio } from '@remotion/media';");
+ expect(result.output).toContain("import { AbsoluteFill } from 'remotion';");
+ expect(result.output).toContain('<Audio');
+ expect(result.output).toContain('src="https://remotion.media/whip.wav"');
+ expect(result.output).not.toContain('staticFile');
+ expect(result.output).not.toContain('@remotion/sfx');
+ } finally {
+ await fs.rm(tempDir, {recursive: true, force: true});
+ }
+});
+
test('rejects inserting an Audio asset if Audio is already defined', async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));
try {
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 6f2ca7ed0c..297bdc0481 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -603,6 +603,7 @@ export type InsertableCompositionElement =
type: 'asset';
assetType: 'image' | 'video' | 'gif' | 'audio';
src: string;
+ srcType?: 'static' | 'remote';
dimensions: {
width: number;
height: number;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index fb08dd8176..67dfb8f548 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -197,6 +197,13 @@ export {
getEffectFieldsToShow,
getFieldsToShow,
} from './schema-field-info';
+export {
+ REMOTION_MEDIA_SFX_PREFIX,
+ SFX_DRAG_MIME_TYPE,
+ isRemotionSfxUrl,
+ parseSfxDragData,
+ type SfxDragData,
+} from './sfx-drag-data';
export type {
AnySchemaFieldInfo,
DragOverrides,
diff --git a/packages/studio-shared/src/sfx-drag-data.ts b/packages/studio-shared/src/sfx-drag-data.ts
new file mode 100644
index 0000000000..843a86115d
--- /dev/null
+++ b/packages/studio-shared/src/sfx-drag-data.ts
@@ -0,0 +1,68 @@
+export const SFX_DRAG_MIME_TYPE = 'application/vnd.remotion.sfx+json';
+
+export const REMOTION_MEDIA_SFX_PREFIX = 'https://remotion.media/';
+
+export type SfxDragData = {
+ type: 'remotion-sfx';
+ version: 1;
+ sfx: {
+ name: string;
+ url: string;
+ };
+};
+
+const isRecord = (value: unknown): value is Record<string, unknown> => {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+};
+
+export const isRemotionSfxUrl = (value: string): boolean => {
+ try {
+ const url = new URL(value);
+ return (
+ url.protocol === 'https:' &&
+ url.host === 'remotion.media' &&
+ url.href.startsWith(REMOTION_MEDIA_SFX_PREFIX) &&
+ url.pathname.length > 1
+ );
+ } catch {
+ return false;
+ }
+};
+
+export const parseSfxDragData = (value: string): SfxDragData | null => {
+ try {
+ const parsed: unknown = JSON.parse(value);
+ if (!isRecord(parsed)) {
+ return null;
+ }
+
+ if (parsed.type !== 'remotion-sfx' || parsed.version !== 1) {
+ return null;
+ }
+
+ if (!isRecord(parsed.sfx)) {
+ return null;
+ }
+
+ const {name, url} = parsed.sfx;
+ if (
+ typeof name !== 'string' ||
+ name.length === 0 ||
+ typeof url !== 'string' ||
+ !isRemotionSfxUrl(url)
+ ) {
+ return null;
+ }
+
+ return {
+ type: 'remotion-sfx',
+ version: 1,
+ sfx: {
+ name,
+ url,
+ },
+ };
+ } catch {
+ return null;
+ }
+};
diff --git a/packages/studio-shared/src/test/sfx-drag-data.test.ts b/packages/studio-shared/src/test/sfx-drag-data.test.ts
new file mode 100644
index 0000000000..3271bc4894
--- /dev/null
+++ b/packages/studio-shared/src/test/sfx-drag-data.test.ts
@@ -0,0 +1,62 @@
+import {expect, test} from 'bun:test';
+import {
+ isRemotionSfxUrl,
+ parseSfxDragData,
+ type SfxDragData,
+} from '../sfx-drag-data';
+
+const validSfxDragData: SfxDragData = {
+ type: 'remotion-sfx',
+ version: 1,
+ sfx: {
+ name: 'whip',
+ url: 'https://remotion.media/whip.wav',
+ },
+};
+
+test('parses SFX drag data', () => {
+ expect(parseSfxDragData(JSON.stringify(validSfxDragData))).toEqual(
+ validSfxDragData,
+ );
+});
+
+test('validates remotion.media SFX URLs', () => {
+ expect(isRemotionSfxUrl('https://remotion.media/whip.wav')).toBe(true);
+ expect(isRemotionSfxUrl('http://remotion.media/whip.wav')).toBe(false);
+ expect(isRemotionSfxUrl('https://example.com/whip.wav')).toBe(false);
+});
+
+test('rejects invalid SFX drag data', () => {
+ expect(parseSfxDragData('')).toBe(null);
+ expect(parseSfxDragData('{')).toBe(null);
+ expect(
+ parseSfxDragData(
+ JSON.stringify({
+ ...validSfxDragData,
+ version: 2,
+ }),
+ ),
+ ).toBe(null);
+ expect(
+ parseSfxDragData(
+ JSON.stringify({
+ ...validSfxDragData,
+ sfx: {
+ ...validSfxDragData.sfx,
+ name: '',
+ },
+ }),
+ ),
+ ).toBe(null);
+ expect(
+ parseSfxDragData(
+ JSON.stringify({
+ ...validSfxDragData,
+ sfx: {
+ ...validSfxDragData.sfx,
+ url: 'https://example.com/whip.wav',
+ },
+ }),
+ ),
+ ).toBe(null);
+});
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index d223c33e0a..bb5e4b976b 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -1,7 +1,9 @@
import type {Size} from '@remotion/player';
import {
ASSET_DRAG_MIME_TYPE,
+ SFX_DRAG_MIME_TYPE,
parseAssetDragData,
+ parseSfxDragData,
} from '@remotion/studio-shared';
import React, {
useCallback,
@@ -42,6 +44,7 @@ import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';
import {
importAssets,
importRemoteAsset,
+ insertRemoteAudio,
insertExistingAssets,
} from './import-assets';
import {SPACING_UNIT} from './layout';
@@ -84,10 +87,17 @@ const isAssetDragEvent = (event: DragEvent): boolean => {
);
};
+const isSfxDragEvent = (event: DragEvent): boolean => {
+ return Array.from(event.dataTransfer?.types ?? []).includes(
+ SFX_DRAG_MIME_TYPE,
+ );
+};
+
const isRemoteAssetDragEvent = (event: DragEvent): boolean => {
return (
!isFileDragEvent(event) &&
!isAssetDragEvent(event) &&
+ !isSfxDragEvent(event) &&
hasRemoteAssetDragData(event.dataTransfer)
);
};
@@ -101,6 +111,27 @@ const getAssetDragPath = (event: DragEvent): string | null => {
return parseAssetDragData(value)?.assetPath ?? null;
};
+const getSfxDragUrl = (event: DragEvent): string | null => {
+ const {dataTransfer} = event;
+ if (!dataTransfer) {
+ return null;
+ }
+
+ for (const type of [SFX_DRAG_MIME_TYPE, 'application/json', 'text/plain']) {
+ const value = dataTransfer.getData(type);
+ if (!value) {
+ continue;
+ }
+
+ const parsed = parseSfxDragData(value);
+ if (parsed) {
+ return parsed.sfx.url;
+ }
+ }
+
+ return null;
+};
+
const isDragEventInsideCanvas = (event: DragEvent): boolean => {
const {current} = canvasRef;
if (!current) {
@@ -635,6 +666,7 @@ export const Canvas: React.FC<{
!canDropAssets ||
(!isFileDragEvent(event) &&
!isAssetDragEvent(event) &&
+ !isSfxDragEvent(event) &&
!isRemoteAssetDragEvent(event)) ||
!isDragEventInsideCanvas(event)
) {
@@ -657,6 +689,7 @@ export const Canvas: React.FC<{
currentCompositionId === null ||
(!isFileDragEvent(event) &&
!isAssetDragEvent(event) &&
+ !isSfxDragEvent(event) &&
!isRemoteAssetDragEvent(event)) ||
!isDragEventInsideCanvas(event)
) {
@@ -690,6 +723,17 @@ export const Canvas: React.FC<{
compositionFile,
compositionId: currentCompositionId,
});
+ } else if (isSfxDragEvent(event)) {
+ const url = getSfxDragUrl(event);
+ if (url === null) {
+ return;
+ }
+
+ await insertRemoteAudio({
+ url,
+ compositionFile,
+ compositionId: currentCompositionId,
+ });
} else {
const url = getRemoteAssetUrlFromDataTransfer(event.dataTransfer);
if (url === null) {
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index f963260502..92585fa5ba 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -1,6 +1,7 @@
import {
detectFileType,
getRequiredPackageForInsertableElement,
+ isRemotionSfxUrl,
type DownloadRemoteAssetResponse,
type FileType,
type InsertableCompositionElement,
@@ -369,6 +370,50 @@ export const importRemoteAsset = async ({
}
};
+export const insertRemoteAudio = async ({
+ compositionFile,
+ compositionId,
+ url,
+}: {
+ compositionFile: string;
+ compositionId: string;
+ url: string;
+}) => {
+ if (!isRemotionSfxUrl(url)) {
+ showNotification('Cannot add sound effect: Unsupported URL', 3000);
+ return;
+ }
+
+ const element: InsertableCompositionElement = {
+ type: 'asset',
+ assetType: 'audio',
+ src: url,
+ srcType: 'remote',
+ dimensions: null,
+ };
+
+ try {
+ const inserted = await insertAssetElement({
+ compositionFile,
+ compositionId,
+ element,
+ });
+
+ if (!inserted) {
+ return;
+ }
+
+ notifyInsertedAssets([getAssetLabel(element)]);
+ } catch (error) {
+ showNotification(
+ `Could not add sound effect: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ 4000,
+ );
+ }
+};
+
export const insertExistingAssets = async ({
assetPaths,
compositionFile,