Developer Tutorials
Automate B-Roll with AI, JSON, and the Zvid API
Turn an approved shot list into a 12-second B-roll video. Run the Node.js example, keep source trims separate from output timing, and use AI to plan new shots.
By Mina RamzyPublished Updated
A good B-roll automation starts with shot decisions. Record what each supporting clip should show, when it should appear, and which part of the source to use. Then let code turn that cue sheet into a video.
This walkthrough builds a 12-second coffee sequence with three approved clips and the Zvid API. You will run a complete Node.js example, validate its credit estimate, render once and download the MP4. An optional AI prompt helps plan new shots; the supplied example already has its footage selected.
The sequence you will make
The example is a silent vertical video, 720 × 1280 at 30 frames per second. Beans, espresso and milk each get four seconds, with a short label over the picture. These clips illustrate a coffee sequence; they do not document one continuous preparation.
Watch the action change with each label.
- 0 to 4 seconds: beans pouring into a grinder. “Start with the beans.”
- 4 to 8 seconds: espresso flowing from a spout. “Pull the espresso.”
- 8 to 12 seconds: milk pouring into coffee. “Make it your moment.”
The script assembles supporting footage. It does not transcribe speech, generate footage, add a voiceover, insert cutaways into an existing talking-head video or publish to a social account.
1. Get the runnable example
You need Node.js 22 or newer with npm, a Zvid account, an API key from app.zvid.io/api-keys, and enough credits for the render. Run the code on your computer or server so the key stays private. All three sample media URLs are supplied; no upload or AI account is needed.
Budget 12 render credits for the unchanged sequence. Building the request locally and running API validation do not consume render credits. Rendering spends credits. The script checks the current estimate and stops above its configured 12-credit ceiling. See how Zvid calculates render credits for changes to duration or resolution.
Extract the ZIP and open a terminal inside its automated-b-roll folder, where package.json is located. Install the pinned official @zvid/sdk dependency and build the request:
node --version
npm ci
npm run build
The last command writes out/request.json without contacting Zvid. If PowerShell blocks npm.ps1, use npm.cmd instead of npm; you do not need to change your execution policy.
| File | What you use it for |
|---|---|
data/cue-sheet.json |
Approved shots, output intervals, source trims and labels |
data/ai-planning-prompt.txt |
An optional prompt for planning a different sequence |
src/project.js |
Input checks and the reusable scene layout |
src/index.js |
Validation, submission, tracking and download |
out/request.json |
Complete API request generated by npm run build |
2. Set the key and validate
Copy .env.example to a new file named .env in the same folder. In PowerShell, run Copy-Item .env.example .env. On macOS or Linux, run cp .env.example .env.
Open .env and paste your key after ZVID_API_KEY=. Keep the credit ceiling as shown:
ZVID_API_KEY=
MAX_RENDER_CREDITS=12
Commands load this file automatically; existing process environment variables take precedence. Keep the key out of JSON files, browser code and public repositories. The SDK sends it in the x-api-key header to https://api.zvid.io. API key authentication explains the header and credential setup.
Run:
npm start
For the unchanged sample, expect:
Valid: true. Estimated credits: 12.
No render submitted.
Open out/validation.json to inspect the estimate, resolved project and warnings. Correct errors or warnings before rendering. The current response is authoritative if the estimate changes. The ceiling is a check in this example, not an atomic server billing cap; validation does not reserve credits. A valid request also does not establish that a clip is relevant or its crop looks good. The validation guide explains these results.
3. Render and save the MP4
When the estimate is acceptable, run:
npm run render
The script validates again, records the submission attempt, submits one request and saves its job ID. It checks the job every five seconds for up to ten minutes. Each network request also has a timeout.
Wait for state: "completed", even if progress already says 100%. On completion, the command writes out/coffee-broll.mp4. Open it in your video player and watch all three shots. Check the cuts at four and eight seconds, the labels, and whether the action stays visible inside the vertical crop. The absence of sound is intentional.
| Operation | API endpoint | Result to keep |
|---|---|---|
| Validate | POST /api/render/validate/api-key |
Credit estimate and resolved project |
| Submit | POST /api/render/api-key |
Job ID and reserved credits |
| Track | GET /api/jobs/{jobId} |
Completed output or failure reason |
The complete code records the attempt before sending the paid request and disables automatic submission retries. Media downloads receive no API key. Keep your downloaded file before the hosted output expires; see job states and output retrieval.
If tracking or downloading is interrupted, run:
npm run resume
This follows the saved job without starting another render. If submission stopped before saving an ID, check Renders at app.zvid.io first. After finding the existing job, use:
npm run resume -- --job-id YOUR_JOB_ID
Replace YOUR_JOB_ID with that job's ID. A missing response does not prove that no render was created. For a deliberately new video, inspect the previous job, rename out to preserve its records, then edit, validate and render again.
How the cue sheet controls two clocks
A cue sheet is a list of shot decisions. Output time says when a shot appears in the finished video. Source time says which part of the original clip plays.
| Shot | Output interval | Source interval | Scene duration |
|---|---|---|---|
| Beans | 0 to 4 seconds | 2 to 6 seconds | 4 seconds |
| Espresso | 4 to 8 seconds | 1 to 5 seconds | 4 seconds |
| Milk | 8 to 12 seconds | 4 to 8 seconds | 4 seconds |
Here is the first record from data/cue-sheet.json:
{
"id": "beans",
"start": 0,
"end": 4,
"visualIntent": "Coffee beans fall into a grinder hopper.",
"clipUrl": "https://cdn.zvid.io/blog/automated-b-roll/168b50cad380/beans.mp4",
Collapse example
{
"id": "beans",
"start": 0,
"end": 4,
"visualIntent": "Coffee beans fall into a grinder hopper.",
"clipUrl": "https://cdn.zvid.io/blog/automated-b-roll/168b50cad380/beans.mp4",
"sourceBegin": 2,
"sourceEnd": 6,
"sourceDuration": 16,
"label": "Start with the beans",
"approved": true
}
The builder calculates duration = end - start, maps sourceBegin and sourceEnd to the VIDEO element's videoBegin and videoEnd, and places each shot in its own Zvid scene. Every scene starts its local timeline at zero. Scenes play in array order, so the second shot needs no global enterBegin: 4.
The important video fields become:
{
type: 'VIDEO',
src: shot.clipUrl,
videoBegin: shot.sourceBegin,
videoEnd: shot.sourceEnd,
enterBegin: 0,
Collapse example
{
type: 'VIDEO',
src: shot.clipUrl,
videoBegin: shot.sourceBegin,
videoEnd: shot.sourceEnd,
enterBegin: 0,
exitEnd: duration,
width: 720,
height: 1280,
position: 'center-center',
resize: 'cover',
speed: 1,
volume: 0
}
resize: "cover" fills the frame and can crop the source. volume: 0 mutes embedded sound so it cannot compete with narration you may add later. The Video Elements reference explains trimming, crop and speed settings.
The sample uses hard cuts: 4 + 4 + 4 equals 12 seconds. Adding two half-second crossfades would overlap the scenes and reduce their sequence to 11 seconds. Do not add transitions to a narration-aligned cue sheet without recalculating its timing.
The builder requires contiguous shots, normal playback speed, matching source-window lengths, approval flags and labels of up to 40 characters. These are this example's application rules, not universal Zvid requirements. They keep timing easy to audit. sourceDuration is a recorded inspection value; the script does not measure remote files or verify licensing. Setting approved: true records your review decision rather than proving it.
Use AI to propose shots, then approve the media
AI can turn an idea into concrete visual intents and useful search phrases. It should not invent a clip URL, declare that footage is licensed, or mark a shot approved. For a new sequence, paste the included prompt into your preferred AI assistant. Its essential instruction is:
Plan supporting shots for a silent 12-second coffee sequence.
0-4 seconds: coffee beans.
4-8 seconds: espresso extraction.
8-12 seconds: milk in a cup.
Return id, start, end, visualIntent and searchQuery for each beat.
Use concrete visible actions. Keep the timing unchanged.
Do not invent media URLs, trim times, licenses or approval flags.
For the espresso beat, a useful search phrase is “espresso flowing from machine spout”. “Morning energy” is too vague to specify a visible action. Search your own library or Zvid's stock library, then inspect the candidates.
Before adding a new clip to the cue sheet:
- Watch the source and choose a continuous window that shows the intended action.
- Check the vertical crop, including the first and last frame of that window.
- Confirm the usage rights and any required attribution for your destination.
- Supply a stable, publicly accessible media URL and record its duration and trim times.
- Set
approvedtotrueonly after review, then build and validate the request.
Keep the selected URLs and timings fixed when resuming a job. Re-running an AI search during recovery can silently change the video you are trying to finish. AI planning is optional, is not called by the supplied script, and may incur separate costs from the AI service you choose.
For narration-led work, finish the audio and obtain real sentence timings before planning the shots. Prepared timed captions can follow the same transcript. The JSON subtitle walkthrough covers that separate step; this B-roll example does not perform transcription.
Replace one shot without changing the design
After the first successful render, edit one record in data/cue-sheet.json. Keep its start and end values to preserve the sequence. Replace its URL, source trim, source duration, visual intent and label together, then review the new crop and approve it.
The supplied files are available as beans footage, espresso footage and milk footage. They are already hosted for this example. When switching to your own footage, follow the media URL requirements.
The reusable layout lives in src/project.js. It produces concrete scene JSON, so this walkthrough needs no saved template. For a larger service, template variables and scene iteration provide another way to reuse a design. Keep the approved cue sheet as the record of what each render should show.
Troubleshoot the failed stage
| Symptom | What to do |
|---|---|
review the footage and set approved to true |
Review the source and crop. The builder is enforcing the example's approval flag. |
shots must be contiguous and start at zero |
Check adjacent start/end values. This sample does not allow timing gaps. |
the source trim must match the shot duration |
Make the source window as long as the output interval. Check it fits inside the source. |
| HTTP 401 | Check the key in .env, including any process environment override. |
Estimate exceeds MAX_RENDER_CREDITS |
Inspect the changed duration and quote before intentionally raising the ceiling. |
Job state is failed |
Read failedReason in out/job.json and fix that cause before a new submission. |
| Polling or download stopped | Use npm run resume to track the existing job. |
For a job-specific problem, keep its ID and contact https://zvid.io/contact. Do not send your API key.
Frequently asked questions
Does this example use AI to generate B-roll footage?
No. The example renders three supplied video clips with Zvid. Its optional AI prompt proposes visual intents and search phrases for new footage; a person still selects clips, checks rights and records trim times. The Node.js script makes no AI-generation calls.
Can I add this B-roll automatically to an existing talking-head video?
This example creates a separate B-roll sequence; it does not insert cutaways into an existing talking-head edit. That workflow needs the original video's audio and timeline, plus explicit windows for the supporting shots. Use actual narration timing when planning those windows.
Why are videoBegin and videoEnd different from start and end?
videoBegin and videoEnd select a window inside the source clip. The cue sheet's start and end describe the finished video's timeline. The espresso shot appears from 4 to 8 seconds in the output while playing source seconds 1 to 5.
Do I need a saved Zvid template to render the cue sheet?
No. The example converts the cue sheet into a complete project and sends it inside the request's payload. Its reusable design is a local JavaScript function. A stored template is an optional way to manage reusable designs, not a prerequisite for this render.
How many Zvid credits does the B-roll example use?
The unchanged 12-second, 720 × 1280 example has a 12-credit render estimate. Building JSON, API validation and checking an existing job do not submit a new render. Run npm start for the current estimate before npm run render; optional AI planning has separate provider costs.
How do I recover an interrupted B-roll render without submitting it again?
Run npm run resume when out/run.json contains the saved job ID. If submission ended before saving an ID, locate the job in the dashboard and use npm run resume -- --job-id YOUR_JOB_ID. Inspect the previous job before starting a deliberately new render.