Branchwell

Become a Pro / website · becomeapro.ai / scripts / make-audio.mjs

Raw 1.8 KB on 0104128d30a01b5156cca2446fd234b2f1fa3673
1// Makes a small mp3 for every <Say word="..."> in the lessons that does not have one yet.
2// Needs ELEVENLABS_API_KEY in the environment. Voice: Quentin (clear, neutral narrator), eleven_multilingual_v2.
3// Usage: ELEVENLABS_API_KEY=... node scripts/make-audio.mjs
4import fs from "fs";
5import path from "path";
6
7const VOICE = "Aa6nEBJJMKJwJkCx8VU2";
8const OUT = "public/audio";
9const key = process.env.ELEVENLABS_API_KEY;
10if (!key) throw new Error("Set ELEVENLABS_API_KEY");
11
12// Same rule as src/lib/audio.ts
13const slug = (text) => text.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80).replace(/-+$/g, "");
14
15const words = new Set();
16(function walk(dir) {
17 for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
18 const full = path.join(dir, entry.name);
19 if (entry.isDirectory()) walk(full);
20 else if (entry.name.endsWith(".mdx")) {
21 for (const m of fs.readFileSync(full, "utf8").matchAll(/<Say\s+word=(?:"([^"]+)"|'([^']+)'|\{"([^"]+)"\})/g)) words.add(m[1] ?? m[2] ?? m[3]);
22 }
23 }
24})("content/lessons");
25
26fs.mkdirSync(OUT, { recursive: true });
27let made = 0;
28for (const word of words) {
29 const file = path.join(OUT, `${slug(word)}.mp3`);
30 if (fs.existsSync(file)) continue;
31 const res = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${VOICE}?output_format=mp3_22050_32`, {
32 method: "POST",
33 headers: { "xi-api-key": key, "Content-Type": "application/json" },
34 body: JSON.stringify({ text: word, model_id: "eleven_multilingual_v2", voice_settings: { stability: 0.5, similarity_boost: 0.75 } }),
35 });
36 if (!res.ok) throw new Error(`ElevenLabs ${res.status} for "${word}": ${await res.text()}`);
37 fs.writeFileSync(file, Buffer.from(await res.arrayBuffer()));
38 made++;
39}
40console.log(`${words.size} clips needed, ${made} made`);