Code-Driven Video Production with AI: A Practical Guide to Programmatic Rendering
This guide explains how to produce videos programmatically by having AI coding agents write code that computes each frame, rather than relying on generative video models. It covers the core principle that a video is a set of functions sampled over time, ready-to-use prompt skeletons for five content formats (news packages, goal analysis, ink-wash animation, 3D showcases, and pixel RPG), an AI-generated audio pipeline for voiceover and music, a reusable seven-step workflow, memory-management techniques for long-running projects, and cloud rendering for batch production. It also lists common pitfalls to avoid. After reading, you will understand how to build video pipelines that are deterministic, locally editable, reproducible, and scalable.
Introduction: Have AI “Write Code to Compute Frames,” Not Just “Generate Frames”
When most people think about making video with AI, their first instinct is to type a prompt and let a generative video model produce a few seconds of footage. That route does lower the barrier to entry, but the moment you want videos that can be repeatedly edited and delivered reliably as a production pipeline, you quickly hit three problems:
- Consistency is hard to guarantee: When one video is generated in several segments, characters, scenes, lighting, and style easily jump between shots.
- Local edits are expensive: To change one color scheme, one line of copy, or one set of data, you often have to regenerate the entire clip.
- Determinism is missing: The same prompt produces different results on two runs, making version comparison and issue reproduction difficult.
There is another route that is rapidly gaining adoption: instead of generating frames, write code that “computes” them.
- Every pixel in the video is produced by a deterministic program evaluated at a given point in time.
- Text, charts, lines, 3D models, and pixel characters all exist as editable code objects.
- Voiceover is produced by speech synthesis, background music is produced by a music-generation model, and both are aligned with the visuals along a timeline.
In the past, this route required creators to master both programming and video production. Today, once you describe the requirements clearly, an AI coding agent can write the code, run it, read the errors, and debug them without you typing a single line yourself. This does not mean you no longer need to think. Quite the opposite: breaking a scene down into objects that can be precisely described in code is the core of this skill.
Based on several kinds of practice samples that have emerged recently (news packaging, goal analysis, ink-wash style, 3D showcases, and pixel RPGs), this article systematically covers the principles, workflows, prompt methods, and engineering practices of code-driven video generation.
1. The Principle: Video Is a Set of Functions Sampled Over Time
To understand code-rendered video, you only need to grasp one core idea: a video is the result of sampling a frame function at different moments in time.
Let the frame function be frame(t), where t is time. At 30 frames per second, for example, the system calls frame(t) once every 1/30 second, encodes the returned result as an image, concatenates all the images in order, and adds an audio track to produce the final video.
From this, three practical principles follow:
- The frame must be determined by
talone. If rendering the same moment twice produces different results, the function is usually using an unseeded random number or the system clock, and that must be eliminated. - All motion is interpolation. Position, scale, opacity, and color are all functions of
t, and pairing them with easing curves makes motion feel intuitive. - Audio and video can be generated independently, then orchestrated together. Voiceover, music, and visuals are each generated against time codes, then aligned on the timeline at the end.
The following sample code shows a clip with a “title sliding in, a ball flying along a parabola, and a badge fading in”:
FPS = 30 # Frame rate: determines time sampling densityWIDTH, HEIGHT = 1920, 1080def frame(t):# The scene depends only on time t: rendering the same t twice must yield identical resultsscene = Canvas(WIDTH, HEIGHT)# 1. Title: slides in from the bottom during 0~0.8s; ease_out makes the deceleration feel naturalp = clamp01(t / 0.8)ease = 1 - (1 - p) ** 3 # easeOutCubicscene.add(text("Quarterly revenue grows steadily", x=120, y=300 + (1 - ease) * 200,size=72, alpha=p))# 2. Moving object: flies along a parabola during 1~2.5s, opacity fades with progressif 1.0 <= t <= 2.5:q = (t - 1.0) / 1.5x = 200 + q * 1500y = 800 - 600 * 4 * q * (1 - q) # Parabolic trajectoryscene.add(circle(x, y, r=18, alpha=1 - q))# 3. Badge: fades in starting at 2.8sscene.add(badge("Source: public financial reports", alpha=clamp01((t - 2.8) / 0.4)))return scene.render()# Batch render, then use a video codec tool to encode into formats such as MP4render_video(frame, fps=FPS, duration=6, output="demo.mp4")
With the help of an AI coding agent, creators only need to describe “what effect they want”; the agent handles function decomposition, time-parameter design, easing implementation, and rendering and encoding. If you are unhappy with a detail, such as “the title slides in too fast” or “the ball’s arc is not pronounced enough,” you only propose a change to that segment of code and the rest is unaffected. This characteristic of being locally editable and globally reproducible is precisely the biggest advantage of programmatic video over generative video.
2. Five Sample Types: Prompt Skeletons for Different Content Formats
Different content formats place very different demands on visuals, pacing, and technical approach. Rather than describing everything from scratch each time, it is better to distill a fixed skeleton for each sample type. An effective sample prompt usually contains seven parts:
- Role and goal: State the role (e.g., “a senior motion graphics designer”) and the intended use.
- Technical specs: Resolution, frame rate, duration, and aspect ratio.
- Visual standards: Color scheme, fonts, materials, lighting effects, and whitespace.
- Storyboard list: Write out time, visuals, action, transitions, voiceover, and sound effects for each segment.
- Audio requirements: Voiceover timbre and pace, and music style with emotional beats.
- Delivery requirements: Produce keyframes for confirmation first, then render the full video.
- Constraints and acceptance: Compliant asset sources, no overlapping visual elements, and a checklist of checks.
Below are five prompt skeletons you can use directly.
2.1 News Packaging: Code-Driven Data Visualization
The core of news packaging is accurate information, clear hierarchy, and steady pacing. All numbers, charts, and title bars should be generated from data rather than “drawn” on, so that when the data changes, the visuals update automatically.
You are a senior news channel packaging designer. Please produce a [60]-second news feature, aspect ratio [1920×1080], frame rate [25].
Visual standards: [dark blue gradient background; channel red as the primary color; sans-serif fonts for Chinese titles; a unified logo in the top-left corner, a scrolling caption bar at the bottom, and a time badge in the bottom-right corner].
Storyboard requirements:
- [0~4s] Channel opener: the logo is outlined and grown in from lines, with a band of light sweeping from left to right.
- [4~14s] The main title assembles from several color blocks; keywords are highlighted in an accent color, and a thin line expands from the center outward beneath it.
- [14~34s] Data readout: a line chart is drawn point by point from left to right; values scroll up to their target and then lock in, with units and data source labeled in sync.
- [34~48s] Map annotations: multiple nodes on the map light up in sequence, and the connecting lines grow in turn.
- [48~60s] End card: the main title and date are centered, and the whole scene fades out.
Audio requirements: [a steady male voiceover; low-frequency tense background music; a short “whoosh” added at transitions].
Acceptance requirements: [first output one keyframe per shot for my confirmation, then render the full video; all text must stay within the safe area; numbers and sources must be traceable].
2.2 Goal Analysis: Multiple Angles, Slow Motion, and Trajectory Annotations
Goal analysis is a form of “reproducing a physical process with code.” Trajectories, angles, and distances can all be computed precisely by code, which is more accurate than drawing frame by frame by hand and easier to modify.
You are a football tactics analysis animator. Please produce a [45]-second goal-breakdown video, aspect ratio [1920×1080], frame rate [25].
The video has three segments:
- [0~8s] Top-down view: a 2D pitch diagram where players are represented by numbered dots; use interpolation to show the runs before the goal, with key players highlighted.
- [8~30s] Side-view slow motion: slow down the footage with the moment of the strike as the time origin, drawing the ball’s parabolic trajectory and height changes; freeze the keyframes [strike, contact, goal] for 0.4 seconds each with a white circle to emphasize them.
- [30~45s] Review annotations: return to the top-down view and overlay pass-route arrows and angle arcs, labeling [shot angle, ball speed, number of touches].
Audio requirements: [commentary-style male voiceover; the music pauses for 0.5 seconds at the moment of the strike and rises to a climax after the goal].
Acceptance requirements: [trajectory lines must not cover the players; the slow-motion segment must not drop frames; use the assumption values you provide and label them clearly].
2.3 Ink-Wash Style: Simulating “Ink Charm” with Noise and Brushstrokes
The difficulty with ink-wash painting lies in making it look “authentic.” Programmatic rendering is naturally good at regular shapes but ill-suited to random, natural brushstrokes. The key is to use multi-layer noise, semi-transparent overlays, and jittery curves to simulate the density variation and “flying white” of a brush.
You are a digital ink-wash animator. Please produce a [30]-second ink-wash-style short film, aspect ratio [1920×1080].
Visual standards: [rice-paper textured background with subtle fiber grain; all elements use ink tones only, with five density levels — light, thin, heavy, dark, and clear; line edges may have slight jitter and flying white, and a smooth “plastic” gradient is forbidden; vermilion seals are used only as accents].
Storyboard requirements:
- [0~8s] Distant mountains gradually emerge from faint ink, moving from blurred to solid, with mist flowing slowly across the scene.
- [8~18s] In the foreground, a branch of plum blossoms is outlined with jittery curves, and the petals on the branch appear one by one using a “dot ink” technique.
- [18~26s] The main subject gradually recedes into the whitespace, leaving only a vertical signature line, followed by a stamped seal.
- [26~30s] The whole scene fades out.
Transition requirements: [ink blooms outward from the center, revealing the next scene].
Audio requirements: [guqin sparse notes as accents; keep the whitespace quiet, do not fill the whole film with music].
Acceptance requirements: [first produce 3 style keyframes for my confirmation, then render the full video].
2.4 3D Showcases: From Generated Assets to Interactive Web Pages
The 3D workflow is the longest: generate assets with a generation model or procedural modeling, arrange lighting and cameras in the scene, render out video or real-time frames, and finally integrate into a web page, game, or product showcase page. What most needs to be trained here is not prompt-writing skill but the ability to break vague ideas into clear requirements, using a fixed structure:
- I want to make [what object];
- Its shape should reflect [key feature 1, key feature 2];
- Use [reference image / style description] as the basis;
- It will ultimately be used for [web / game / product showcase];
- Please generate the model first, then help me integrate it into the project and open it to check.
After the model is generated, add three questions in sequence:
- Which parts need to be separated? (e.g., the segments of armor, or a product’s shell and internal components)
- What interactions need to be supported? (rotation, zoom, click to view, exploded view)
- What else are you unsatisfied with? (proportions, materials, detail density)
You are a 3D asset and frontend engineer. Please generate a model based on the requirements above and integrate it into my web project:
- Output a common 3D model format, split by component into objects that can be controlled independently, with clear naming preserved.
- The left side of the page is the 3D view, and the right side is a parts list; clicking a list item highlights the corresponding part.
- Provide interactions such as [an auto-rotate toggle, click-to-explode a part, and double-click to reset].
- When done, open the page and self-check: [whether the model loads correctly, whether the number and names of parts are correct, and whether the interactions work].
If you encounter a step that the tools cannot complete, state it clearly and provide an alternative.
The 3D route can also be used directly to “produce a video”: arrange a camera path and lighting animation in the scene, then render frame by frame at a fixed resolution to obtain product demos, mechanical explanations, or architectural walkthrough videos.
2.5 Pixel RPG: Precise Control of Pixel Grids and Color Palettes
Pixel art looks simple, but it actually places the highest demands on “precision”: pixel alignment, integer scaling, and a limited color palette. Any anti-aliasing anywhere will ruin the aesthetic. These constraints are also best handed to an AI coding agent, because it can strictly compute the position of every pixel.
You are a pixel-game artist and animation engineer. Please produce a [40]-second pixel-RPG-style short film:
- Logical resolution [320×180], scaled up by an integer factor to [1920×1080], with anti-aliasing and smooth scaling forbidden throughout.
- The color palette is limited to [16 colors], primarily [deep blue night, teal-green grass, beige dirt roads, vermilion cloaks].
- Characters are [8×16-pixel] sprites, with 2 idle frames and 4 walking frames for each of the four directions.
- Storyboard: [0~8s] title screen, “PRESS START” blinking, the starry sky changing once every 2 seconds;
[8~22s] top-down view, the character walks along the dirt road into the village entrance, with footsteps producing a slight vertical bounce, and the surrounding flowers and grass swaying in a 2-frame loop;
[22~34s] a dialog box pops up, the text displays character by character with a “beep” sound;
[34~40s] enter combat, the character swings the sword producing a white slash line, and the enemy flashes white and dissolves.
Audio requirements: [8-bit-style square-wave music and sound effects].
Acceptance requirements: [no blurry pixels when zoomed in; the color palette must not exceed 16 colors; first produce 1 keyframe per shot for my confirmation].
Save these five skeletons as templates, and each time just replace the content in the [brackets], and the output quality of your prompts will stay stable. Once you accumulate about ten sets, you can basically cover most short-video and demo-video needs.
3. Audio: Generate Voiceover and Music with AI, Then Align with the Visuals
Code rendering solves the “visuals”; sound requires a separate pipeline, and it too can be completed end-to-end by AI. The audio pipeline can be divided into three layers:
- Voiceover layer: Generated by speech synthesis from the narration script. A good voiceover prompt should specify the persona (e.g., “a steady news anchor” or “a passionate sports commentator”), the speaking pace, where to pause, and which keywords need emphasis.
- Music layer: Generated by a music-generation model by style, mood, and rhythm; the more specific the description, the higher the chance of a usable result. For example, “tech-style electronic music, medium tempo, a low-key buildup in the first 4 seconds, drum beats entering from the 8th second, a climax at the 30th second, and 2 seconds of lingering resonance at the end.”
- Sound effects layer: Transition sounds, click sounds, number-ticking sounds, goal-cheering sounds, and so on. These can be listed by time point in the prompt or selected from an audio asset library.
After the layers are generated, they go into mixing. A common practice is to keep the voiceover the clearest, the music secondary, and the sound effects as finishing touches, and to use dynamic processing so the music automatically drops in volume when the voiceover appears. The final levels and loudness should be adjusted according to the target publishing platform’s requirements.
Sound is not just a backdrop; it can also drive the rhythm of the visuals. The sample code below illustrates this:
# 1. Synthesize the voiceover and get per-sentence timestampsaudio, segments = tts(text="In Q3, the company's revenue grew 12% year over year.",voice_style="calm male anchor",speed=1.0,)# segments look like: [(start, end, sentence), ...]# 2. Allocate video segments according to the duration of each sentencescenes = []for start, end, sentence in segments:scenes.append(Scene(visual=visual_for(sentence),start=start, end=end))# 3. Align transitions with the pauses between sentences, and auto-duck the BGM under the voicevideo = compose(scenes, bgm="tech_upbeat", ducking=True)render_video(video, fps=25, duration=audio.duration, output="final.mp4")
In practice, the recommended approach is “finalize the narration script, then synthesize the voiceover, and finally arrange the visuals to match the voiceover’s length.” If you build the visuals first and add the voiceover later, any change in the voiceover’s length forces you to rework the entire timeline. For news and review-style content, this “sound-drives-visuals” approach is both stable and ensures information completeness.
4. From Requirements to Finished Video: A Reusable Workflow
Stringing these methods together yields a complete production pipeline with seven stages:
- Define the use and specs. First determine the publishing context and aspect ratio: a landscape long video, a portrait short video, or a demo page; then determine resolution, frame rate, duration, language, and subtitle requirements.
- Break down the storyboard. Have AI expand a one-sentence requirement into a shot-by-shot script, spelling out the time, visuals, action, voiceover, and sound effects for each shot, and review it manually before writing any code.
- Choose the technical route. For layout- and graphics-and-text-centric work, choose a browser rendering framework; for data- and graphics-centric work, choose a general-purpose programming language plus a codec tool; for 3D content, add a 3D engine.
- Implement and preview one shot at a time. Have AI implement only one shot each time, render a few keyframes to confirm the effect, and avoid drifting further in the wrong direction.
- Synthesize audio and arrange the timeline. Synthesize the voiceover and music, adjust shot timing to match the voiceover’s length, and unify the transitions.
- Render and quality-check the full video. Render the complete video, check the resolution, duration, audio levels, and whether text is out of frame, and use logging and monitoring/alerting services to track failed tasks.
- Deliver and archive. Name and output the finished video following a unified convention, and archive the engineering code, parameter configs, and prompts together for easy reuse.
In this workflow, “feeding requirements bite by bite” is far more effective than “handing over everything in one sentence”:
- First give the overall framework (style + storyboard) and confirm the direction;
- Then give detailed requirements shot by shot (the color of an element, how it moves, when it appears);
- Finally, handle revision feedback in one batch (what is wrong and how you want it adjusted).
Each step produces an inspectable intermediate result, so errors can be caught and corrected within the smallest possible scope.
5. Helping AI “Remember” the Project: Requirement Templates and Memory Management
Video projects often span days or even weeks. As content accumulates in the same AI session, two typical symptoms appear:
- Getting “dumber”: Early agreements get buried under a large volume of intermediate conversation, and the AI starts omitting style rules or repeating problems that have already been fixed.
- Getting “more expensive”: Every exchange must carry the full history; the longer the context, the higher the cost and the slower the response.
The industry has proposed one idea for this: let AI, when idle, “replay” and organize its memory like a person dreaming, distilling scattered conversations into structured knowledge. In day-to-day practice, you can start from three angles.
5.1 Use a Project Instruction File as “Long-Term Memory”
Maintain an instruction file in the project root that records the following:
- The project goal and publishing context;
- The visual standards (color scheme, fonts, layout);
- The technical route and directory structure;
- Confirmed key decisions and their reasons;
- Pitfalls encountered and their solutions.
Each time you start a new session, first have AI read this file, then begin work. This avoids having to “re-explain the whole project from scratch every time you open a new session.”
5.2 Organize Memory by Stage
After each stage ends, use the prompt below to have AI do a “review” and write the results into the instruction file:
Please read all the engineering files in this project and the recent conversation records, and compile a project memory document containing:
- The project goal and the work completed so far;
- Key decisions and their reasons (e.g., why the current technical route was chosen, why a certain transition is used for a certain type of shot);
- Pitfalls encountered and their corresponding solutions;
- Unresolved issues and next to-dos.
Once organized, update the instruction file in the project root, and tell me which content was merged or deleted and why.
The key points of organizing are deduplication, attribution, and completion: merge duplicate content, add reasons for decisions, and fill in to-dos that are easy to forget. What AI can remember is always only what has been explicitly written into the file, so “having AI write it down” is more reliable than “having AI remember it.”
5.3 Use Layered Memory to Control Context
Not all content needs to stay in context at all times; you can layer it by lifecycle:
| Layer | Content | Lifecycle | How to Use |
|---|---|---|---|
| Long-term memory | Project goals, visual standards, technical route | The entire project cycle | Written to the project instruction file; read at the start of new sessions |
| Mid-term memory | Key decisions, pitfall records | A single stage | Organized by stage and periodically consolidated |
| Short-term memory | Current task, recent changes | A single session | Discarded once done; keep only the conclusions |
This way, you avoid both “not remembering” and “remembering too much.”
6. Cloud Rendering: From “Making One Video” to “Batch Production”
Once the workflow runs smoothly, the next step is usually scaling up: swapping in different data into the same set of templates to generate dozens of pieces of content, or moving the rendering tasks to the cloud. At this point, you can use the idea of “separating parameters from rendering”:
- Separate parameters from rendering: Templates define only structure and animation; data, copy, and assets are fed in as configuration.
- Queue tasks: Rendering tasks enter a queue and are consumed in sequence by rendering nodes according to load, avoiding saturating local resources.
- Store outputs uniformly: Assets and finished videos are stored in object storage; rendering nodes scale elastically through a container platform; runtime logs are collected by a logging service; and failures and backlogs are caught promptly through monitoring and alerting.
- Accelerate content delivery: When finished videos are published, a content delivery network reduces wait times for end users.
- Notify via callback: Once rendering completes, a message notification syncs the result to the business system or the creator.
These capabilities are supported by corresponding general-purpose products on mainstream cloud platforms such as Baidu AI Cloud. Template rendering itself is relatively CPU-intensive and has clear task boundaries, which makes it very well suited to being turned into a cloud-based batch-processing pipeline.
7. Common Pitfalls and Things to Watch Out For
- Treating AI as a “one-shot generator.” A single conversation rarely produces an ideal finished video; treat it as a collaborator that needs multiple rounds of communication.
- Not fixing the random seed. If the same prompt produces different results on two runs, it is most likely because the random number is unseeded, and subsequent revisions will have nothing to compare against.
- Doing visuals first and adding voiceover later. Building the visuals first and adding the voiceover afterward means even a small change in duration forces a full retiming of the timeline, which is highly inefficient.
- Chasing a one-and-done result. Every shot should have a preview step; the earlier a problem is caught, the lower the rework cost.
- Ignoring font and asset licensing. Fonts, music, and image assets have different license scopes, so confirm each one before commercial use. In addition, in line with the requirements for labeling generated/synthetic content, AI-generated or deep-synthesized audio and video should be labeled as required by the applicable regulations to avoid compliance risk.
- Relying on AI self-checking alone. AI can catch obvious errors, but the final video still needs a human review, especially for critical content such as text, numbers, and brand information.
Conclusion
The value of “having AI write code to compute frames” lies not only in writing less code, but also in turning video production from “creating from scratch each time” into a reproducible, editable, and batch-capable engineering process:
- The visuals are determined by code, so every change is traceable;
- The sound is generated by AI, then aligned with the visuals on the timeline;
- The requirements are constrained by templates, so AI can produce stable output;
- The memory is carried by files, so a project can be sustained over the long term;
- The rendering runs in the cloud, so capacity can scale on demand.
A good starting point is a real 15–30-second short film: use the prompt skeletons in this article to describe the requirements, have AI generate the code and render the keyframes, then finish the voiceover and music, and finally output the finished video. After you get one complete workflow running end to end, gradually move the templates, parameters, and rendering tasks to the cloud.
