Say you're building a clipping tool. A user pastes a link and wants every moment where someone says a certain phrase, as separate MP4s. You need two things for that: the video file, and a transcript with timestamps so you know where to cut.
The cutting part is easy. Find the sentences that contain the phrase, take their start and end times, and hand them to ffmpeg. The script below does that in about 80 lines of Node 18+ with no npm dependencies.
Getting the file and the timestamps is where it usually gets annoying. Downloading from YouTube or TikTok works on your laptop and then gets blocked once it runs on a server, and the timestamps mean wiring up a separate speech-to-text step. I built Importly for this, so the script uses one Importly import to get both back from the link. Swap in your own source if you already have the file and a timed transcript.
The script
import { spawnSync } from 'node:child_process'
import { mkdirSync, writeFileSync } from 'node:fs'
const [url, phrase] = process.argv.slice(2)
const PAD = 0.5 // seconds of context before and after each sentence
const API = 'https://api.importly.io'
const headers = {
Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
'Content-Type': 'application/json',
}
const fail = (message) => {
console.error(message)
process.exit(1)
}
const importWithTranscript = async (link) => {
const res = await fetch(`${API}/import`, {
method: 'POST',
headers,
body: JSON.stringify({
url: link,
videoQuality: '720p',
compatibleCodecs: true, // H.264 + AAC: plays and edits everywhere
includeTranscript: true,
transcriptMode: 'ai', // speech-to-text: sentence-level timestamps
maxCostDollars: 1.0,
}),
})
const body = await res.json()
if (!res.ok || !body.success) fail(`Import not started: ${body.code} ${body.error}`)
const { jobId } = body.data
while (true) {
const status = await fetch(`${API}/import/status?id=${jobId}`, { headers })
const { data } = await status.json()
if (data.status === 'completed') return data.result
if (data.status === 'failed') fail(`Import failed: ${data.code} ${data.message}`)
await new Promise((resolve) => setTimeout(resolve, 5000))
}
}
const matchingSegments = (transcript, text) => {
const needle = text.toLowerCase()
return transcript.data.segments.filter((s) => s.text.toLowerCase().includes(needle))
}
const download = async (mediaUrl, path) => {
const res = await fetch(mediaUrl)
if (!res.ok) fail(`Download failed: HTTP ${res.status}`)
writeFileSync(path, Buffer.from(await res.arrayBuffer()))
}
const cut = (source, start, end, out) => {
// Re-encode so the clip starts exactly on the sentence, not on the nearest keyframe
const run = spawnSync('ffmpeg', [
'-y', '-loglevel', 'error',
'-ss', Math.max(start - PAD, 0).toFixed(2), '-to', (end + PAD).toFixed(2),
'-i', source,
'-c:v', 'libx264', '-preset', 'veryfast', '-c:a', 'aac',
out,
], { stdio: 'inherit' })
if (run.status !== 0) fail(`ffmpeg failed on ${out}`)
}
const result = await importWithTranscript(url)
const transcript = result.transcript ?? {}
if (transcript.status === 'skipped') fail(`No transcript: ${transcript.reason}`)
const matches = matchingSegments(transcript, phrase)
if (matches.length === 0) fail(`"${phrase}" isn't said in "${result.title}"`)
mkdirSync('clips', { recursive: true })
await download(result.mediaUrl, 'clips/source.mp4')
const slug = phrase.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
matches.forEach((seg, i) => {
const out = `clips/${slug}-${i + 1}.mp4`
cut('clips/source.mp4', seg.start, seg.end, out)
console.log(`${out} ${seg.start.toFixed(1)}-${seg.end.toFixed(1)}s "${seg.text}"`)
})
console.log(`Cost: $${result.totalCostInDollars}`)
Run it with a link and a phrase:
# needs ffmpeg: apt install ffmpeg, or brew install ffmpeg
IMPORTLY_API_KEY=your_api_key node cut-clips.mjs "https://www.youtube.com/watch?v=jNQXAC9IVRw" "elephants"
clips/elephants-1.mp4 1.4-3.6s "All right, so here we are, one of the elephants."
Cost: $0.02
A few choices worth explaining
The cut re-encodes. -c copy is much faster, but it starts on the nearest keyframe, which can be a couple of seconds before the sentence. For a short clip, re-encoding takes a moment and lands exactly on the sentence. PAD adds half a second on each side so the first and last words don't get cut off.
compatibleCodecs: true asks for H.264 video with AAC audio. Without it you can get AV1 or VP9 at the same resolution, which is smaller but doesn't play or edit everywhere.
maxCostDollars caps the job. A long video plus speech-to-text costs more than a short clip, and a job that would go over the cap fails before anything is downloaded, so you only pay the $0.003 price check.
The matching is a plain substring search. That's the part your app will actually change: a keyword list, a search index over the segments, or an LLM that reads the transcript and picks the best moments by timestamp.
download reads the whole file into memory. Fine for short videos. For long ones, stream it to disk with pipeline(Readable.fromWeb(res.body), createWriteStream(path)).
In a real app
Don't poll inside a web request. Start the import from your API route with a webhook URL and cut the clips in a background worker when it calls back. If users will come back for more clips from the same video, keep the source in your own bucket so you don't fetch it twice.
The full recipe, with the error cases to handle and a Python version, is in the docs: https://www.importly.io/docs/recipes/clips-by-phrase-node
Top comments (1)
Cutting by what is said rather than by timecode is a really practical idea for repurposing long recordings. Adding a second or so of padding on each side of a match usually keeps the cuts from feeling abrupt.