How to Generate NPC Dialogue for Games with TTS API?

By EchoSprite editorial team · Updated 2026-11-18

This guide shows game developers how to replace static voice lines with dynamic NPC dialogue using the EchoSprite TTS API. You will learn a practical workflow to generate high-quality speech from text, reducing production costs and scaling content without hiring live voice actors. The API integrates easily into existing game engines via a simple HTTP interface.

We cover everything from choosing the right voice preset to handling API responses and optimizing for performance. Whether you are building a small indie title or a larger project, this page provides concrete steps to implement scalable NPC audio. You will see exactly how to prepare text, manage rate limits, and test your integration using the free trial credit.

How to Generate NPC Dialogue for Games with TTS API?

Frequently asked questions

What is TTS API?

It is a cloud text-to-speech API. Send text via POST to /v1/audio/speech and receive an audio file. It uses the same request shape as the OpenAI speech endpoint, so official OpenAI SDKs work by changing the base_url to https://api.play48x.com/v1 and using your API key.

How do I choose a voice?

Select from 8 presets: Aria, Nova, Luna, Sage, Felix, Milo, Atlas, or Orion. Each has a distinct tone, from warm narrator to deep documentary. Voices are based on licensed recordings and carry an inaudible synthetic watermark. Use GET /v1/voices to see all available options and their characteristics.

Can I generate dialogue in real-time?

No streaming or WebSocket support exists. Requests are processed sequentially, so under load a request may wait in a queue. Typical speed is roughly real-time on long texts, but short phrases take a few seconds. You must wait for the full audio file response.

What is the character limit?

Each request accepts up to 4096 characters of text. Spaces and punctuation count toward this limit. For longer dialogues, split your text into parts of 4096 characters or less and join the resulting audio files after generation.

How do I handle errors?

If synthesis fails, the charge is returned in full. Failed requests are free. Check the response status to determine if generation succeeded. You can retry the request or split the text if it exceeds limits.

Do I need to pre-generate audio?

No. You can generate audio on-demand by sending text to the API. However, pre-generating dialogue is efficient for static NPC lines. Generated audio is returned in the response and not stored by the API.

Can I adjust the speed?

Yes, set the speed field between 0.25 and 4.0. This allows you to speed up or slow down the NPC dialogue to match gameplay pacing or emotional context without changing the voice preset.

What languages are supported?

Supports 23 languages including English, Spanish, German, Japanese, and Chinese. Any voice can speak any supported language. If language is unset, it guesses from the script; set it explicitly for non-English Latin text. Vietnamese and Thai are not supported.

Is streaming supported?

No. The API does not support streaming, WebSockets, or real-time partial audio. You receive the complete audio file after generation. Use the standard HTTP response to handle the audio data in your game engine.

Can I clone a voice?

No custom voice cloning is offered. You cannot upload your own voice or design custom voices. You must choose from the 8 available presets: Aria, Nova, Luna, Sage, Felix, Milo, Atlas, or Orion.

How do I pay?

Pay with USDT on the TRON network (TRC-20). Minimum top-up is $5, credited automatically within minutes. No cards or PayPal. Balance does not expire. Pricing is $10 per 1 million characters.

Is there a free trial?

Yes, signing in with Google gives $0.50 credit (about 50,000 characters) valid for 7 days. Email/password accounts start without trial credit. Top-ups add to your balance for ongoing usage.

What formats are available?

Choose from mp3, wav, opus, flac, or pcm. Select the response_format field in your request. These formats cover most game engine requirements for audio playback.

How do I integrate with Unity?

Use the OpenAI SDK or plain HTTP. Change the base_url to https://api.play48x.com/v1 and use your API key. Send text via POST to /v1/audio/speech and load the returned audio file into Unity.

Why use TTS for NPCs

Sound wave illustration for: Why use TTS for NPCs

Text-to-speech technology offers game developers a practical alternative to traditional voice acting. By generating NPC dialogue programmatically, studios can significantly reduce production overhead while maintaining high audio quality. This approach is particularly valuable for indie teams and startups looking to allocate resources efficiently without sacrificing immersion.

Reduce voice acting costs

Traditional voice recording requires hiring actors, booking studios, and managing post-production. With a TTS API, you pay only for characters processed, eliminating upfront studio fees. The cost is predictable: $0.01 per 1,000 characters, with no monthly minimums or seat licenses. Failed requests are free, ensuring you only pay for usable audio.

  • No studio booking fees or actor retainers
  • Pay-per-use model eliminates unused audio costs
  • Failed synthesis charges are fully refunded

Generate dynamic responses

TTS enables real-time dialogue generation based on player choices or environmental triggers. Since the API synthesizes speech on demand, NPCs can react dynamically to in-game events without pre-recording every possible permutation. This creates a more responsive and immersive world where dialogue feels immediate and context-aware.

  • Supports dynamic dialogue trees and branching narratives
  • Generates unique responses for varying player inputs
  • Enables contextual voice lines without pre-recording every variant

Scale content production

As your game grows, so does the volume of NPC dialogue. TTS allows you to generate thousands of lines quickly without scaling voice talent. You can pre-generate assets during loading screens or generate them on the fly for limited scenarios. This scalability ensures consistent audio quality across large casts without logistical bottlenecks.

  • Generate unlimited dialogue lines without hiring more voice actors
  • Pre-generate assets during loading screens to minimize runtime latency
  • Easily add new characters by selecting from 8 distinct voice presets

Choosing the right voice

Sound wave illustration for: Choosing the right voice

Selecting the correct voice preset defines your NPC’s personality without hiring additional talent. Our eight voices cover a wide range of archetypes, from warm narrators to energetic announcers, ensuring every character sounds distinct and appropriate for their role.

You can combine these presets with speed adjustments to further customize delivery. Whether you need a calm instructional guide or a deep documentary-style narration, the API handles the synthesis instantly.

Match character personality

Assign voices based on narrative function. Aria provides a warm, clear narrator tone ideal for exposition. Luna offers a soft, storytelling quality for lore-heavy games. Sage delivers a calm, instructional voice perfect for tutorials or guide NPCs.

For more dynamic interactions, use Felix for energetic promos or Milo for friendly, conversational dialogue. Atlas remains neutral for news-style updates, while Orion adds depth for serious, documentary-style content.

  • Aria: warm, clear narrator
  • Nova: bright, upbeat
  • Luna: soft, storytelling
  • Sage: calm, instructional
  • Felix: energetic, promo
  • Milo: friendly, conversational
  • Atlas: neutral, news
  • Orion: deep, documentary

Use Aria for narrators

Aria is optimized for clear, warm narration, making it ideal for quest logs, historical backgrounds, or overarching story commentary. Her voice cuts through game audio mixes without sounding overly dramatic.

Pair Aria with a moderate speed (1.0–1.5) for natural pacing. This voice works well for any character delivering exposition or guiding the player through the world.

Use Felix for energetic promos

Felix brings high energy to in-game advertisements, quest alerts, or hype sequences. His preset is designed to grab attention quickly, making it suitable for dynamic events or promotional NPCs.

Use Felix with a slightly elevated speed (1.2–1.5) to enhance the upbeat feel. This voice is particularly effective for short, punchy lines that need to convey urgency or excitement.

Preparing your text

Sound wave illustration for: Preparing your text

Before sending text to the API, ensure each input string does not exceed 4,096 characters. The API processes requests sequentially, so keeping inputs within this limit ensures predictable processing times and avoids truncation errors during synthesis.

Keep under 4096 characters

Each API request accepts a maximum of 4,096 characters for the input field. Spaces, punctuation, and special characters all count toward this limit. Exceeding this threshold will cause the request to fail.

Split long dialogues

For dialogue trees exceeding the character limit, split the text into smaller chunks before sending requests. Generate audio for each segment separately, then join the resulting audio files in your game engine. This approach maintains synchronization and allows for dynamic branching without hitting API constraints.

Include speed tags if needed

Adjust the speed parameter between 0.25 and 4.0 to match character personality or urgency. Faster speeds suit energetic voices like Felix for promos, while slower rates work well for Sage’s instructional tone. Experiment with different speeds to ensure lip-sync accuracy in your engine.

Making the API call

Sound wave illustration for: Making the API call

Sending text to the speech engine requires a standard HTTP POST request to the dedicated endpoint. This method transmits your character dialogue data, allowing game engines to receive audio files ready for immediate playback.

The request structure mirrors the OpenAI speech endpoint, making integration straightforward for developers already familiar with similar APIs. You simply direct your POST call to the correct base URL, ensuring the system knows exactly where to route the synthesis job.

Use POST method

Direct your request to POST https://api.play48x.com/v1/audio/speech. This endpoint is designed specifically for accepting text payloads and returning synthesized audio files. Using the correct HTTP method ensures the server processes your dialogue lines without routing errors or format mismatches.

The POST method handles the JSON body efficiently, allowing you to send variable-length text strings up to 4096 characters per request. This single-call approach simplifies your game’s audio pipeline, reducing the need for complex multi-step retrieval processes.

  • Endpoint: POST https://api.play48x.com/v1/audio/speech
  • Method: HTTP POST
  • Payload: JSON body

Set JSON body correctly

Construct your request body with the required fields: model, input, voice, and response_format. The input field contains your NPC dialogue text, while voice selects from the eight available presets like Aria or Felix. The model field accepts either tts-1 or tts-1-hd, both using the same engine.

You can also include optional parameters like speed (0.25–4.0) to adjust pacing or language to specify an ISO code. If you omit the language, the system guesses it from the script, defaulting to English for Latin text, but explicit setting is recommended for non-English lines.

Ensure your text does not exceed 4096 characters. If a dialogue branch is longer, split it into multiple requests and join the resulting audio files in your game engine. This keeps each API call lightweight and within rate limits.

  • Required: model, input, voice, response_format
  • Optional: speed, language
  • Max text length: 4096 characters

Include your Bearer key

Authentication is handled via the Authorization header. Include your unique API key in the format Authorization: Bearer tts-.... This key is generated when you sign up and is active until you issue a new one, which immediately deactivates the old key.

Without this header, the API will reject your request with a 401 error. Ensure the key is sent with every request, especially when making batch calls for large dialogue trees. One key per account simplifies management for small teams and startups.

Keep your key secure in your game’s build configuration or environment variables. Since each key allows 60 requests per minute, monitor your usage to avoid hitting rate limits during intensive generation phases.

  • Header: Authorization: Bearer tts-...
  • One active key per account
  • 60 requests per minute limit

Handling the response

Sound wave illustration for: Handling the response

The API returns the synthesized audio directly in the response body, allowing you to capture the binary data immediately. This streamlined process eliminates the need for polling or additional fetch calls, letting your game engine receive the audio file as soon as synthesis completes.

Save the audio file

Write the incoming binary response directly to a local file or memory buffer. Supported formats include MP3, WAV, OPUS, FLAC, and PCM, so choose the one that best fits your engine’s audio pipeline. Ensure you handle the data stream correctly to avoid corruption.

  • Write binary data to disk or memory immediately
  • Select appropriate format (mp3, wav, opus, flac, pcm)
  • Verify file integrity before loading into the engine

Check for errors

If synthesis fails, the API returns an error code and the charge is returned. Always check the HTTP status code before attempting to parse the audio data. Handling these errors gracefully prevents your game from crashing or displaying silent NPCs when a voice fails to generate.

  • Check HTTP status codes (200 vs 4xx/5xx)
  • Handle failed requests where charges are refunded
  • Implement retry logic for transient network issues

Play in game engine

Load the generated audio file into your game engine’s audio system using standard plugins or middleware. Since the API does not support streaming, pre-generated files are ideal for static NPC lines. For dynamic responses, ensure your engine can handle on-demand file loading without significant lag.

  • Load audio via standard engine plugins
  • Use pre-generated files for static dialogue
  • Test loading times for dynamic responses

Optimizing performance

Sound wave illustration for: Optimizing performance

Pre-generate dialogue during loading screens to hide synthesis latency. Since short phrases take a few seconds to generate, pre-baking lines ensures instant playback when the player interacts with an NPC. This avoids stuttering or delayed audio feedback during critical gameplay moments.

Use caching for repeated lines to save both time and credits. If an NPC says the same phrase multiple times, store the generated audio file locally and reuse it. This reduces API calls and keeps your balance intact for unique, dynamic responses.

Pre-generate during loading screens

Pre-generate dialogue during loading screens to hide synthesis latency. Since short phrases take a few seconds to generate, pre-baking lines ensures instant playback when the player interacts with an NPC. This avoids stuttering or delayed audio feedback during critical gameplay moments.

For open-world games, batch-generate common phrases (e.g., 'Welcome', 'Go left') while the player traverses large areas. This shifts the computational load from real-time interaction to background processes, maintaining a smooth immersive experience.

  • Batch generate common phrases during load screens.
  • Shift synthesis load from real-time to background.
  • Pre-bake lines to avoid playback stuttering.

Use caching for repeated lines

Use caching for repeated lines to save both time and credits. If an NPC says the same phrase multiple times, store the generated audio file locally and reuse it. This reduces API calls and keeps your balance intact for unique, dynamic responses.

Implement a simple hash-based cache keyed by voice, text, speed, and format. This ensures consistent audio output for identical inputs while minimizing unnecessary API usage.

  • Store generated audio for repeated phrases.
  • Use hash-based caching for consistency.
  • Reduce API calls to save credits.

Monitor rate limits

Monitor rate limits to prevent request throttling. You have 60 requests per minute per key (10 per minute before the first top-up). Exceeding this limit may delay synthesis or drop requests.

Implement exponential backoff in your game engine’s audio manager. If a request fails due to rate limits, wait and retry automatically. This ensures resilience without manual intervention during peak usage.

  • Limit: 60 requests/minute per key.
  • Backoff strategy for failed requests.
  • Retry logic for rate limit delays.
Optimizing performance

Managing languages

Sound wave illustration for: Managing languages

Precise language control ensures NPCs sound authentic across global markets. By explicitly setting the language parameter, you guarantee the correct pronunciation and intonation, especially when the input text uses Latin script but is not English.

Set language parameter explicitly

Always specify the ISO code for non-English Latin text. Without this, the API defaults to English, which may cause awkward pronunciations for French, German, or Spanish dialogue lines.

Auto-detect for Latin scripts

If you omit the language field, the system guesses based on the script. Latin text defaults to English, while other scripts trigger their respective languages automatically.

Support for 23 languages

The API supports Arabic, Chinese, Danish, Dutch, English, Finnish, French, German, Greek, Hebrew, Hindi, Italian, Japanese, Korean, Malay, Norwegian, Polish, Portuguese, Russian, Spanish, Swahili, Swedish, and Turkish. Any voice can speak any of these languages.

  • Vietnamese, Indonesian, Thai, Ukrainian, Romanian, Czech, and Bengali are not supported.

Testing your integration

Sound wave illustration for: Testing your integration

Testing your integration begins with the free trial credit. Upon signing in via Google, you receive $0.50, covering approximately 50,000 characters valid for 7 days. This allows you to verify API connectivity and basic synthesis without financial commitment. Ensure your account is active before sending requests to avoid unexpected billing issues when you scale.

Use this trial period to validate your workflow end-to-end. Generate a few short phrases to confirm that your game engine correctly receives and plays the audio files. Check that the request payload matches the expected JSON structure and that the Bearer token is correctly formatted in the Authorization header.

Use free trial credit

Sign in with Google to activate $0.50 in trial credit, valid for 7 days. This covers about 50,000 characters, enough to test multiple voices and formats. Email-based accounts start without this credit, so ensure you use the Google sign-in method for immediate access.

Verify your balance and characters remaining on the dashboard before testing. This ensures you have sufficient credits for your initial integration tests without risking actual funds.

  • Credit expires after 7 days.
  • Available only with Google sign-in.
  • Covers ~50,000 characters.

Test with short phrases

Generate short dialogue lines to verify latency and audio format handling. Short phrases typically take a few seconds to process, allowing you to gauge real-time responsiveness. Use different voices like Aria or Felix to ensure the correct tone is applied.

Check that the API returns the audio file directly in the response. Ensure your game engine can handle the specified response_format (e.g., mp3 or wav) without requiring additional conversion steps.

  • Test voices: Aria, Felix, Luna.
  • Verify response formats: mp3, wav.
  • Check processing latency.

Verify audio quality

Listen to the generated audio to confirm clarity and language accuracy. Ensure the language parameter is set correctly, especially for non-English text, to avoid incorrect pronunciation. The audio should match the expected voice preset and speed settings.

Check for the inaudible synthetic watermark, which marks the file as AI-generated. This helps in identifying AI dialogue in post-production or marketing materials if needed.

  • Set language explicitly.
  • Verify voice preset matches.
  • Check synthetic watermark.

Scaling for production

Sound wave illustration for: Scaling for production

Moving from prototype to live deployment requires a reliable funding method and clear visibility into your consumption. Since EchoSprite does not support credit cards or subscriptions, you must top up your balance using USDT on the TRON network (TRC-20). Transfers are credited automatically within minutes, allowing your game to continue generating dialogue without interruption once your initial trial credit expires.

Top up with USDT

USDT on the TRON network (TRC-20) is the only accepted payment method. The minimum top-up amount is $5, and credits appear in your account automatically within minutes of the transfer confirmation. This method supports unlimited scaling without monthly fees or minimum spend requirements, ensuring you only pay for the NPC lines you actually generate.

Monitor usage metrics

Track your character count and request volume via the dashboard to avoid unexpected pauses. You are limited to 60 requests per minute per API key, which drops to 10 per minute for new accounts before the first top-up. Monitoring these metrics helps you anticipate queue delays, especially since requests are processed sequentially and may wait under load.

  • Check balance and characters left on /get-api-key/
  • Watch the 60 requests/minute limit per key
  • Note that failed requests are free and do not count against usage

Adjust speed settings

Fine-tune the speed parameter (0.25–4.0) to match your game’s pacing and save on character costs. Generating speech at higher speeds reduces the duration of the audio file, though our API charges strictly by character count ($0.01 per 1,000 characters). Experiment with voices like Felix for energetic promos or Atlas for neutral news to find the optimal balance between delivery speed and audio quality.

Common pitfalls

Sound wave illustration for: Common pitfalls

Developers often assume TTS APIs behave like live voice actors, leading to runtime crashes or awkward pauses. The two most frequent issues are hitting character limits and expecting real-time audio streams.

By understanding the specific constraints of our API, you can design robust dialogue systems that handle edge cases gracefully without manual intervention.

Ignoring character limits

Each request supports a maximum of 4096 characters. If your NPC line exceeds this, the API will reject the payload or truncate silently depending on implementation.

Split long dialogues into smaller chunks and join the resulting audio files programmatically to maintain continuity.

  • Count spaces and punctuation as characters
  • Pre-split text before sending
  • Use concatenation for long responses

Not handling errors

Failed synthesis requests are free, but your game still needs to handle the error response to avoid silent failures.

Always check the HTTP status code and retry logic for transient network issues or rate limit hits.

Assuming streaming support

This API does not support WebSocket or real-time partial audio streams. You receive the full audio file after processing completes.

Pre-generate audio during loading screens or cache repeated lines to minimize latency for instant playback.

Example use cases

Sound wave illustration for: Example use cases

TTS APIs enable dynamic NPC interactions without recording thousands of unique voice lines. By generating speech on demand, developers can create responsive dialogue trees where characters react specifically to player choices, reducing the logistical overhead of live voice acting.

This approach allows for infinite variations in tone and pacing. Characters can deliver urgent warnings, casual banter, or detailed lore explanations instantly, adapting to the game’s narrative flow without pre-rendered audio files.

Use cases demonstrate practical applications across different genres. The following examples illustrate how specific voice presets and parameters enhance immersion in popular gaming scenarios.

Fallout-style dialogue trees

Implement branching dialogue where each decision triggers a unique vocal response. Use the sage voice for a calm, instructional tone during exposition or the atlas voice for neutral news-style updates. This ensures consistent character personality across thousands of potential conversation paths without storing massive audio libraries.

  • Branching paths trigger unique voices
  • Consistent character personality
  • No massive audio libraries

FNAF jump scare voices

Generate sudden, high-intensity audio cues for horror games. Use felix for energetic, promo-style scares or aria for clear, startling narrator interruptions. Set the speed parameter to 2.0 or higher for abrupt, jarring effects that startle players without requiring complex sound design assets.

  • Sudden high-intensity cues
  • Energetic promo-style scares
  • Abrupt startling effects

Far Cry 6 NPC interactions

Create diverse local flavor for open-world environments. Use nova for bright, upbeat interactions or milo for friendly, conversational banter. Support 23 languages, allowing NPCs to speak in regional dialects dynamically. This scales content production significantly, as each NPC can have unique dialogue without recording sessions for every line.

  • Diverse local flavor
  • Regional dialect support
  • Scaled content production

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. Our AI powers lifelike non-player characters that drive immersive gaming experiences for the next generation of interactive entertainment startups.

Avatar of the voice aria
ariafemale
Avatar of the voice nova
novafemale
Avatar of the voice luna
lunafemale
Avatar of the voice sage
sagefemale
Avatar of the voice felix
felixmale
Avatar of the voice milo
milomale
Avatar of the voice atlas
atlasmale
Avatar of the voice orion
orionmale

23 languages

Any voice speaks any of these languages.

Sources and further reading

  1. Wikipedia
  2. Tether (USDT)
  3. curl documentation
  4. FFmpeg documentation
  5. openai-node on GitHub
  6. OpenAI API reference: create speech
  7. LibriTTS-R corpus (OpenSLR 141)
  8. TRON developer hub: TRC-20
  9. Python documentation
  10. Creative Commons Attribution 4.0
  11. ISO 639 language codes
  12. MDN: Web Speech API

More on this site