Preloader
Others
  • Estimated reading time: 9 Minutes

How to Generate AI Avatar Videos in Batches with Node.js

How to Generate AI Avatar Videos in Batches with Node.js

An AI avatar can be integrated into web applications or backend services to generate presenter videos from text or prerecorded audio. When processing multiple scripts, developers must manage asynchronous jobs, failures, and file retrieval without duplicating tasks or losing progress.

This tutorial uses Node.js and the VisionStory API to build a batch video workflow. It covers resource discovery, job tracking, sequential processing, and MP4 storage.

Setting Up an AI Avatar API Integration

The integration needs an API key, valid resource IDs, and a place to store job records. The examples below use Node.js 24 and build one file, avatar-pipeline.mjs, using built-in modules. No additional packages are required.

Configure API Authentication

VisionStory authenticates requests through the X-API-Key header. API keys currently require a Pro plan or above.

Set the key in the terminal that will run the script. For PowerShell:

$env:VISIONSTORY_API_KEY = "<your_api_key>"

The key belongs in the backend environment. Browser code and public repositories should never contain it.

Start avatar-pipeline.mjs with these imports and a small request helper:

import { randomUUID } from 'node:crypto';
import {
  readFile, writeFile, rename, mkdir,
} from 'node:fs/promises';
import { createWriteStream } from 'node:fs';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';

const base = 'https://openapi.visionstory.ai';
const key = process.env.VISIONSTORY_API_KEY;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

async function api(path, payload, timeout = 30000) {
  if (!key) throw new Error('Set VISIONSTORY_API_KEY first.');

  const response = await fetch(base + path, {
    method: payload ? 'POST' : 'GET',
    headers: {
      'X-API-Key': key,
      'Content-Type': 'application/json',
    },
    body: payload ? JSON.stringify(payload) : undefined,
    signal: AbortSignal.timeout(timeout),
  });

  const text = await response.text();
  let body;
  try {
    body = JSON.parse(text);
  } catch {
    body = {};
  }

  if (!response.ok) {
    const error = new Error(
      body.error?.message || `HTTP ${response.status}`,
    );
    Object.assign(error, {
      status: response.status,
      apiError: body.error,
      retryAfter: response.headers.get('retry-after'),
    });
    throw error;
  }

  if (!body.data) {
    throw new Error('Missing response data; reconcile this request.');
  }
  return body.data;
}

The helper checks the HTTP response, retains structured API errors, and limits each request’s waiting time.

Retrieve Available Avatars and Voices

The VisionStory API quickstart identifies three discovery endpoints:

async function discover() {
  for (const path of [
    '/api/v1/avatars?is_public=true&limit=20',
    '/api/v1/voices?locale=en&limit=20',
    '/api/v1/models',
  ]) {
    console.log(path, JSON.stringify(await api(path), null, 2));
  }
}

Select an avatar from data.avatars, a voice from data.public_voices, and a model from data.models. Paginated avatar and voice responses provide next_cursor when more results are available.

Save valid selections in environment variables:

$env:VISIONSTORY_AVATAR_ID = "<selected_avatar_id>"
$env:VISIONSTORY_VOICE_ID = "<selected_voice_id>"
$env:VISIONSTORY_MODEL_ID = "<selected_model_id>"

For this example, select a model supporting 9:16 and 720p. Resource IDs come from discovery; example placeholders are not usable IDs.

Generating Your First AI Avatar Video Through an API

A first submission establishes the pattern used throughout the pipeline: prepare the input, save a request identifier, submit the job, and record its video ID.

An AI avatar generator handles rendering. Your application maintains the relationship between that rendering task and the user’s original script.

Prepare the Video Generation Request

The main parameters serve distinct purposes:

Parameter Purpose Input requirement
avatar_id Selects the on-screen performer Use an accessible avatar ID
model_id Selects the rendering model Choose supported settings from model discovery
text_script Supplies written text and a voice Includes text and voice_id
audio_script Supplies prerecorded audio Uses audio_url or inline_data
aspect_ratio Sets the frame shape Must be supported by the model
resolution Sets the output resolution Must be supported by the model
client_request_id Identifies a submission for safe retries Keep the same value when retrying that submission

Each request uses either text_script or audio_script. Text input requires both the script and voice ID.

Prerecorded audio can use a publicly reachable URL. Alternatively, inline_data contains the audio’s mime_type and Base64-encoded bytes in data, without a data URL prefix.

Submit the First Video Generation Task

The following function submits the saved payload and reads data.video_id:

async function submit(job) {
  if (job.video_id) return;

  job.first_attempt_at ||= Date.now();

  if (Date.now() - job.first_attempt_at >= 86400000) {
    throw new Error(
      'Idempotency window expired; reconcile before resubmitting.',
    );
  }

  job.status = 'submitting';
  await saveJobs();

  const result = await api('/api/v1/video', job.payload);

  if (!result?.video_id) {
    throw new Error('Missing video_id; reconcile this job.');
  }

  job.video_id = result.video_id;
  job.submitted_at = new Date().toISOString();
  job.status = 'submitted';
  await saveJobs();
}

A successful submission confirms that the request was accepted. Video generation continues asynchronously, and a later status query determines whether the output is ready.

Store the Returned Video ID

Store the script ID, payload, request ID, video ID, status, and submission time together. The tutorial uses jobs.json for a single local worker:

let jobs;

try {
  jobs = JSON.parse(await readFile('jobs.json', 'utf8'));
} catch (error) {
  if (error.code !== 'ENOENT') throw error;
  jobs = {};
}

async function saveJobs() {
  await writeFile('jobs.json.tmp', JSON.stringify(jobs, null, 2));
  await rename('jobs.json.tmp', 'jobs.json');
}

A production service should use its application database. Multiple workers must not independently overwrite this example’s JSON file.

Building a Batch AI Avatar Video Processing Workflow

Batch processing starts with separate jobs for separate scripts. VisionStory’s Talking Avatar API accepts individual generation requests; the batch behavior comes from your application’s queue and records.

This example processes one video through submission, generation, and download before advancing. That keeps the number of active rendering jobs controlled as well as the number of HTTP requests.

Convert Multiple Scripts into Individual API Requests

Each script receives a stable application ID and its own client_request_id:

function prepareJob(script) {
  if (!jobs[script.id]) {
    jobs[script.id] = {
      script_id: script.id,
      status: 'pending',
      payload: {
        avatar_id: process.env.VISIONSTORY_AVATAR_ID,
        model_id: process.env.VISIONSTORY_MODEL_ID,
        text_script: {
          text: script.text,
          voice_id: process.env.VISIONSTORY_VOICE_ID,
        },
        aspect_ratio: '9:16',
        resolution: '720p',
        client_request_id: randomUUID(),
      },
    };
  }

  return jobs[script.id];
}

The saved payload is reused on subsequent runs. Changed text or settings should receive a new application job ID so an existing record does not silently represent different content.

Control Task Queues and Concurrent Requests

The worker records successful and rejected jobs independently. A confirmed generation failure allows the worker to continue; an uncertain submission or unresolved job pauses the queue for later investigation.

async function runBatch(scripts) {
  for (const name of [
    'VISIONSTORY_AVATAR_ID',
    'VISIONSTORY_VOICE_ID',
    'VISIONSTORY_MODEL_ID',
  ]) {
    if (!process.env[name]) throw new Error(`Set ${name} first.`);
  }

  for (const script of scripts) prepareJob(script);
  await saveJobs();

  for (const script of scripts) {
    const job = jobs[script.id];
    if (['stored', 'failed', 'rejected'].includes(job.status)) continue;

    try {
      await submit(job);
      let url;
      const deadline = Date.now() + 600000;

      while (Date.now() < deadline) {
        const remaining = deadline - Date.now();

        const result = await api(
          `/api/v1/video?video_id=${encodeURIComponent(job.video_id)}`,
          undefined,
          Math.min(30000, remaining),
        );

        job.status = result.status;
        await saveJobs();

        if (result.status === 'failed') break;

        if (result.status === 'created') {
          if (!result.video_url) {
            throw new Error('Missing video_url.');
          }

          url = result.video_url;
          break;
        }

        if (!['queued', 'creating'].includes(result.status)) {
          throw new Error(`Unexpected status: ${result.status}`);
        }

        await sleep(
          Math.min(5000, Math.max(0, deadline - Date.now())),
        );
      }

      if (!url && job.status !== 'failed') {
        throw new Error(
          'Still processing; resume with the saved video_id.',
        );
      }

      if (!url) {
        console.error('Generation failed:', job.script_id, job.video_id);
        continue;
      }

      job.file = await downloadVideo(url, job.video_id);
      job.status = 'stored';
      await saveJobs();
      console.log(job.script_id, job.video_id, job.file);
    } catch (error) {
      if (!job.video_id &
          [400, 422].includes(error.status)) {
        job.status = 'rejected';
        job.error = error.apiError || { message: error.message };
        await saveJobs();

        if ([400, 422].includes(error.status)) continue;
      }

      console.error('Batch paused:', job.script_id, error.message);
      throw error;
    }
  }
}

The worker checks each submitted job until generation finishes, fails, or reaches the ten-minute waiting limit. Completed videos are downloaded before the next script is processed. Saved records allow later runs to resume unfinished work and skip files already stored.

Retrieving and Saving Completed AI Avatar Videos

A finished render becomes useful when the application retrieves it, stores it, and associates it with the originating script. The workflow marks a job stored only after the download finishes.

Retrieve the Finished Video URL

The worker reads video_url when the API reports created, then passes that URL to the download function. Linking retrieval to the completed state ensures that each saved file corresponds to a finished generation task.

Generation completion and local storage are recorded separately. If downloading fails, the saved video ID allows another retrieval attempt without generating the video again.

Download and Store the MP4 File

This downloader streams the response to a temporary file and renames it after completion:

async function downloadVideo(url, videoId) {
  await mkdir('videos', { recursive: true });

  const file = `videos/${encodeURIComponent(videoId)}.mp4`;
  const response = await fetch(url, {
    signal: AbortSignal.timeout(120000),
  });

  if (!response.ok || !response.body) {
    throw new Error(`Download HTTP ${response.status}`);
  }

  await pipeline(
    Readable.fromWeb(response.body),
    createWriteStream(file + '.part'),
  );

  await rename(file + '.part', file);
  return file;
}

The download request sends no API key to the media host. Completed VisionStory videos are retained for seven days, so applications requiring long-term storage should retrieve them within that window.

Maintain Your Own Video Records

GET /api/v1/videos returns the account’s latest videos, up to 100 records, without pagination. It is useful for recent activity but cannot replace a long-term application database.

Add this final block to run discovery, a single job, or ten jobs:

if (process.argv.includes('--discover')) await discover();

if (process.argv.includes('--first') || process.argv.includes('--batch')) {
  const scripts = Array.from({ length: 10 }, (_, index) => ({
    id: `training-${index + 1}-v1`,
    text: `Welcome to training module ${index + 1}. Here is your next lesson.`,
  }));

  await runBatch(
    process.argv.includes('--batch') ? scripts : scripts.slice(0, 1),
  );
}

After combining the snippets in avatar-pipeline.mjs, use:

node avatar-pipeline.mjs --discover
node avatar-pipeline.mjs --first
node avatar-pipeline.mjs --batch

Discovery lists resources. The other commands submit generation jobs and can consume credits. A successful run prints the script ID, video ID, and saved MP4 path.

Conclusion

For a training portal, the useful result is a collection of videos that can be traced back to the right lessons. Giving each script its own job record makes that connection manageable as production grows.

With VisionStory handling avatar rendering, the Node.js workflow organizes submissions, follows each job through completion, and stores the resulting files. The same approach can support other applications that need to produce presenter videos from multiple scripts.

Related articles
ZerkIPTV (Zerk IPTV) Review 2026–2027: Is ZerkIPTV.net Reliable?
2 Dec, 2026
  • Estimated reading time: 4 Minutes
Top 5 Best Samsung FRP Bypass Tools for 2027 (Free & Paid)
2 Dec, 2026
  • Estimated reading time: 6 Minutes
5 Instagram Viewer Tools for Content Research and Profile Browsing
2 Dec, 2026
  • Estimated reading time: 6 Minutes
How to Securely Wipe Your Laptop and Smartwatch Before Selling
2 Dec, 2026
  • Estimated reading time: 9 Minutes
What Happens Under the Hood When AI Builds a Website
2 Dec, 2026
  • Estimated reading time: 6 Minutes
Weekly trending
ZerkIPTV (Zerk IPTV) Review 2026–2027: Is ZerkIPTV.net Reliable?
2 Dec, 2026
  • Estimated reading time: 4 Minutes
Top 5 Best Samsung FRP Bypass Tools for 2027 (Free & Paid)
2 Dec, 2026
  • Estimated reading time: 6 Minutes
How to Generate AI Avatar Videos in Batches with Node.js
2 Dec, 2026
  • Estimated reading time: 9 Minutes
5 Instagram Viewer Tools for Content Research and Profile Browsing
2 Dec, 2026
  • Estimated reading time: 6 Minutes
How to Securely Wipe Your Laptop and Smartwatch Before Selling
2 Dec, 2026
  • Estimated reading time: 9 Minutes
Our Sponsors

Our blog is proudly supported by industry-leading sponsors.