Creating SRT subtitle files for videos is a crucial task for improving accessibility and user engagement. According to AssemblyAI, this can be efficiently achieved using Node.js and the AssemblyAI API. This guide walks through the process step-by-step.
Step 1: Set up Your Development Environment
To begin, ensure you have Node.js 18 or higher installed on your system. Create a new project folder and initialize a Node.js project:
mkdir srt-subtitles
cd srt-subtitles
npm init -y
Open the package.json file and add type: "module",
to use the ES Module syntax. Next, install the AssemblyAI JavaScript SDK:
npm install --save assemblyai
Obtain an AssemblyAI API key from your dashboard and set it as an environment variable:
# Mac/Linux:
export ASSEMBLYAI_API_KEY=<YOUR_KEY>
# Windows:
set ASSEMBLYAI_API_KEY=<YOUR_KEY>
Step 2: Transcribe Your Video
With the environment set up, you can start transcribing your video files. Use a publicly accessible video URL or specify local files. Create a file called index.js
and add the following code:
import { AssemblyAI } from 'assemblyai';
const client = new AssemblyAI({ apiKey: process.env.ASSEMBLYAI_API_KEY });
const transcript = await client.transcripts.transcribe({
audio: "https://storage.googleapis.com/aai-web-samples/aai-overview.mp4",
});
Check for errors and log them:
if (transcript.status === "error") {
throw new Error(transcript.error);
}
Step 3: Generate SRT File
After obtaining the transcript, generate the subtitles in SRT format. Import the necessary module to save the file to disk:
import { writeFile } from "fs/promises";
Then, generate the SRT subtitles and save them:
const srt = await client.transcripts.subtitles(transcript.id, "srt");
await writeFile("./subtitles.srt", srt);
You can customize the captions by specifying the chars_per_caption
parameter:
const srt = await client.transcripts.subtitles(transcript.id, "srt", 32);
await writeFile("./subtitles.srt", srt);
Step 4: Run the Script
Finally, run the script to generate the subtitles:
node index.js
After a few seconds, a new file subtitles.srt
will appear on disk, containing the generated subtitles.
Next Steps
Now that you have your subtitle file, you can upload it to YouTube Studio or configure it in your video player. AssemblyAI also offers various tools to enhance your audio and video applications, which can be explored through their blog and documentation.
Image source: Shutterstock
Credit: Source link