🎥 Make videos programmatically with React
Add image and voice gen
Vlad M052d2f06504a
diff --git a/bun.lock b/bun.lockindex bdf0a70c80..7c53de2c26 100644--- a/bun.lock+++ b/bun.lock@@ -1333,6 +1333,7 @@"zod": "^4.1.12",},"devDependencies": {+ "@elevenlabs/elevenlabs-js": "^2.20.0","@remotion/eslint-config-flat": "workspace:*","@types/prompts": "^2.4.9","@types/react": "19.0.0",@@ -2596,6 +2597,8 @@"@docusaurus/utils-validation": ["@docusaurus/[email protected]", "", { "dependencies": { "@docusaurus/logger": "3.9.1", "@docusaurus/utils": "3.9.1", "@docusaurus/utils-common": "3.9.1", "fs-extra": "^11.2.0", "joi": "^17.9.2", "js-yaml": "^4.1.0", "lodash": "^4.17.21", "tslib": "^2.6.0" } }, "sha512-5bzab5si3E1udrlZuVGR17857Lfwe8iFPoy5AvMP9PXqDfoyIKT7gDQgAmxdRDMurgHaJlyhXEHHdzDKkOxxZQ=="],+ "@elevenlabs/elevenlabs-js": ["@elevenlabs/[email protected]", "", { "dependencies": { "command-exists": "^1.2.9", "node-fetch": "^2.7.0" } }, "sha512-xe3nHHU+P0rNl2a2KKy4iCCLtUFsTksBleYU4afszfJq2jDYvaRAFQ7NCc+/tOduJof4eEm/KQIWM7Y+85+M6Q=="],+"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" } }, "sha512-sbP8GzB1WDzacS8fgNPpHlp6C9VZe+SJP3F90W9rLemaQj2PzIuTEl1qDOYQf58YIpyjViI24y9aPWCjEzY2cg=="],"@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "2.8.1" } }, "sha512-97/BJ3iXHww3djw6hYIfErCZFee7qCtrneuLa20UXFCOTCfBM2cvQHjWJ2EG0s0MtdNwInarqCTz35i4wWXHsQ=="],@@ -4334,6 +4337,8 @@"comma-separated-tokens": ["[email protected]", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],+ "command-exists": ["[email protected]", "", {}, "sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w=="],+"commander": ["[email protected]", "", {}, "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg=="],"common-ancestor-path": ["[email protected]", "", {}, "sha512-L3sHRo1pXXEqX8VU28kfgUY+YGsk09hPqZiZmLacNib6XNTCM8ubYeT7ryXQw8asB1sKgcU5lkB7ONug08aB8w=="],@@ -7442,6 +7447,8 @@"@docusaurus/utils-validation/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],+ "@elevenlabs/elevenlabs-js/node-fetch": ["[email protected]", "", { "dependencies": { "whatwg-url": "5.0.0" } }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],+"@emnapi/core/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],"@emnapi/runtime/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],@@ -9626,6 +9633,8 @@"@docusaurus/utils/p-queue/p-timeout": ["[email protected]", "", { "dependencies": { "p-finally": "1.0.0" } }, "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg=="],+ "@elevenlabs/elevenlabs-js/node-fetch/whatwg-url": ["[email protected]", "", { "dependencies": { "tr46": "0.0.3", "webidl-conversions": "3.0.1" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],+"@eslint/eslintrc/espree/acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA=="],"@firebase/auth-compat/node-fetch/whatwg-url": ["[email protected]", "", { "dependencies": { "tr46": "0.0.3", "webidl-conversions": "3.0.1" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],@@ -11768,6 +11777,10 @@"@docusaurus/utils/@docusaurus/types/@mdx-js/mdx/unist-util-stringify-position": ["[email protected]", "", { "dependencies": { "@types/unist": "3.0.2" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="],+ "@elevenlabs/elevenlabs-js/node-fetch/whatwg-url/tr46": ["[email protected]", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],++ "@elevenlabs/elevenlabs-js/node-fetch/whatwg-url/webidl-conversions": ["[email protected]", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],+"@firebase/auth-compat/node-fetch/whatwg-url/tr46": ["[email protected]", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],"@firebase/auth-compat/node-fetch/whatwg-url/webidl-conversions": ["[email protected]", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],diff --git a/packages/template-ai-video/cli.ts b/packages/template-ai-video/cli.tsindex 4c5f18c9e9..dd1470a32d 100644--- a/packages/template-ai-video/cli.ts+++ b/packages/template-ai-video/cli.ts@@ -7,6 +7,8 @@ import ora from "ora";import chalk from "chalk";import * as dotenv from "dotenv";import {+ generateAiImage,+ generateVoice,getGenerateImageDescriptionPrompt,getGenerateStoryPrompt,openaiStructuredCompletion,@@ -21,6 +23,7 @@ dotenv.config();interface GenerateOptions {apiKey?: string;+ elevenlabsApiKey?: string;title?: string;topic?: string;}@@ -50,6 +53,16 @@ class ContentFS {return p;}+ getImagePath(uid: string): string {+ const dirPath = this.getDir("images");+ return path.join(dirPath, `${uid}.png`);+ }++ getAudioPath(uid: string): string {+ const dirPath = this.getDir("audio");+ return path.join(dirPath, `${uid}.mp3`);+ }+getSlug(): string {return this.title.toLowerCase()@@ -61,6 +74,8 @@ class ContentFS {async function generateStory(options: GenerateOptions) {try {let apiKey = options.apiKey || process.env.OPENAI_API_KEY;+ let elevenlabsApiKey =+ options.elevenlabsApiKey || process.env.ELEVENLABS_API_KEY;if (!apiKey) {const response = await prompts({@@ -78,6 +93,23 @@ async function generateStory(options: GenerateOptions) {apiKey = response.apiKey;}+ if (!elevenlabsApiKey) {+ const response = await prompts({+ type: "password",+ name: "elevenlabsApiKey",+ message: "Enter your ElevenLabs API key:",+ validate: (value) =>+ value.length > 0 || "ElevenLabs API key is required",+ });++ if (!response.elevenlabsApiKey) {+ console.log(chalk.red("API key is required. Exiting..."));+ process.exit(1);+ }++ elevenlabsApiKey = response.elevenlabsApiKey;+ }+let { title, topic } = options;if (!title || !topic) {@@ -139,12 +171,18 @@ async function generateStory(options: GenerateOptions) {const contentFs = new ContentFS(title!);contentFs.saveSlides(storySlides);- const imagesSpinner = ora("Generating images...").start();+ const imagesSpinner = ora("Generating images and voice...").start();+ for (const slide of storySlides) {+ await generateAiImage(slide.imageDesc, contentFs.getImagePath(slide.uid));+ await generateVoice(+ slide.text,+ elevenlabsApiKey!,+ contentFs.getAudioPath(slide.uid),+ );+ break;+ }imagesSpinner.succeed(chalk.green("Images generated!"));- const audioSpinner = ora("Generating audio...").start();- audioSpinner.succeed(chalk.green("Audio generated!"));-const finalSpinner = ora("Generating final result...").start();finalSpinner.succeed(chalk.green("Final result generated!"));diff --git a/packages/template-ai-video/package.json b/packages/template-ai-video/package.jsonindex 65e17bd711..53d17ec77e 100644--- a/packages/template-ai-video/package.json+++ b/packages/template-ai-video/package.json@@ -24,6 +24,7 @@"zod": "^4.1.12"},"devDependencies": {+ "@elevenlabs/elevenlabs-js": "^2.20.0","@remotion/eslint-config-flat": "workspace:*","@types/prompts": "^2.4.9","@types/react": "19.0.0",diff --git a/packages/template-ai-video/src/Root.tsx b/packages/template-ai-video/src/Root.tsxindex 976d9718cc..74f6395c3c 100644--- a/packages/template-ai-video/src/Root.tsx+++ b/packages/template-ai-video/src/Root.tsx@@ -6,7 +6,7 @@ import {} from "remotion";import { AIVideo, aiVideoSchema } from "./AIVideo";import { useEffect, useState } from "react";-import { FPS, WindowsHeight, WindowsWidth } from "./constants";+import { FPS, WindowHeight, WindowWidth } from "./constants";import { loadTimelineFromFile } from "./utils";interface InputProps extends Record<string, unknown> {@@ -44,8 +44,8 @@ export const RemotionRoot: React.FC = () => {component={AIVideo}durationInFrames={frameLength}fps={FPS}- width={WindowsWidth}- height={WindowsHeight}+ width={WindowWidth}+ height={WindowHeight}schema={aiVideoSchema}defaultProps={{timelineFile,diff --git a/packages/template-ai-video/src/components/Background.tsx b/packages/template-ai-video/src/components/Background.tsxindex 7c91cc2875..0bc4c40d64 100644--- a/packages/template-ai-video/src/components/Background.tsx+++ b/packages/template-ai-video/src/components/Background.tsx@@ -1,5 +1,5 @@import { AbsoluteFill, Img, useCurrentFrame } from "remotion";-import { FPS, WindowsHeight, WindowsWidth } from "../constants";+import { FPS, WindowHeight, WindowWidth } from "../constants";import { BackgroundElement } from "../types";const EXTRA_SCALE = 0.2;@@ -38,7 +38,7 @@ export const Background: React.FC<{// const durationFrames = ((item.endMs - item.startMs) * FPS)/1000;const localMs = (frame / FPS) * 1000;- const viewSize = { width: WindowsWidth, height: WindowsHeight };+ const viewSize = { width: WindowWidth, height: WindowHeight };const imageRatio = 1.0;const imgWidth = viewSize.height;diff --git a/packages/template-ai-video/src/constants.ts b/packages/template-ai-video/src/constants.tsindex 53727e0f2e..4457b6f645 100644--- a/packages/template-ai-video/src/constants.ts+++ b/packages/template-ai-video/src/constants.ts@@ -1,4 +1,4 @@export const FPS = 30;-export const WindowsWidth = 1080;-export const WindowsHeight = 1920;+export const WindowWidth = 1080;+export const WindowHeight = 1920;export const IntoFrameDuration = 1;diff --git a/packages/template-ai-video/src/service.ts b/packages/template-ai-video/src/service.tsindex 7edc9e979a..30a97cea79 100644--- a/packages/template-ai-video/src/service.ts+++ b/packages/template-ai-video/src/service.ts@@ -1,20 +1,10 @@-import { VoiceDescriptor } from "./types";import z from "zod";import { createOpenAI } from "@ai-sdk/openai";import { generateObject } from "ai";--export const voices: VoiceDescriptor[] = [- { id: "alloy", name: "Alloy" },- { id: "ash", name: "Ash" },- { id: "ballad", name: "Ballad" },- { id: "coral", name: "Coral" },- { id: "echo", name: "Echo" },- { id: "fable", name: "Fable" },- { id: "nova", name: "Nova" },- { id: "onyx", name: "Onyx" },- { id: "sage", name: "Sage" },- { id: "shimme", name: "Shimme" },-];+import { experimental_generateImage as generateImage } from "ai";+import * as fs from "fs";+import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";+import { CharacterAlignmentResponseModel } from "@elevenlabs/elevenlabs-js/api";let apiKey: string | null = null;@@ -22,17 +12,21 @@ export const setApiKey = (key: string) => {apiKey = key;};-export const openaiStructuredCompletion = async (- prompt: string,- schema: z.ZodType<unknown>,-) => {+const getOpenAiProvider = () => {if (!apiKey) {throw "Missing OpenAI API KEY";}- const openai = createOpenAI({+ return createOpenAI({apiKey,});+};++export const openaiStructuredCompletion = async (+ prompt: string,+ schema: z.ZodType<unknown>,+) => {+ const openai = getOpenAiProvider();const { object } = await generateObject({model: openai("gpt-4.1"),@@ -43,6 +37,23 @@ export const openaiStructuredCompletion = async (return object;};+function saveUint8ArrayToPng(uint8Array: Uint8Array, filePath: string) {+ const buffer = Buffer.from(uint8Array);+ fs.writeFileSync(filePath, buffer as Uint8Array);+}++export const generateAiImage = async (prompt: string, path: string) => {+ const openai = getOpenAiProvider();++ const { image } = await generateImage({+ model: openai.image("dall-e-3"),+ prompt,+ size: `1024x1792`,+ });++ saveUint8ArrayToPng(image.uint8Array, path);+};+export const getGenerateStoryPrompt = (title: string, topic: string) => {const prompt = `Write a short story with title [${title}] (its topic is [${topic}]).You must follow best practices for great storytelling.@@ -76,3 +87,28 @@ export const getGenerateImageDescriptionPrompt = (storyText: string) => {return prompt;};++const saveBase64ToMp3 = (data: string, path: string) => {+ const buffer = Buffer.from(data, "base64");+ fs.writeFileSync(path, buffer as Uint8Array);+};++export const generateVoice = async (+ text: string,+ apiKey: string,+ path: string,+): Promise<CharacterAlignmentResponseModel> => {+ const client = new ElevenLabsClient({+ environment: "https://api.elevenlabs.io",+ apiKey,+ });++ const voiceId = "21m00Tcm4TlvDq8ikWAM";++ const data = await client.textToSpeech.convertWithTimestamps(voiceId, {+ text,+ });++ saveBase64ToMp3(data.audioBase64, path);+ return data.alignment!;+};