AI Gameplay
Unity AI
Text To Speech
Spatial Audio
Unity C#
Audio Streaming
AI NPCs

Production AI NPC Systems in Unity (Part 3): Low-Latency Spatial Audio & Voice Streaming (TTS)

4 min read
Eshan Naithani

In Part 1 and Part 2 of this series, we covered LLM inference selection and structured JSON function calling for behavior trees.

The final element to creating believable AI characters is voice synthesis. Having a 3D NPC speak dynamically generated lines in spatial 3D audio turns a text-based chatbot into a fully immersive game character.

However, waiting for a full 5-sentence audio clip to render before playing causes a 2-second delay. Production systems stream PCM audio chunks via WebSockets or Chunked HTTP directly into Unity's AudioSource queue for sub-300ms speech playback.

In Part 3, we implement a production C# audio streaming manager (AISpatialVoiceStreamer.cs) for low-latency 3D spatial voice synthesis.


1. Spatial Audio Pipeline Architecture

Code
 [AI Text Output] ──► [TTS Streaming API] ──► [PCM Audio Chunks (HTTP/WS)]
                                                     │
                                                     ▼
 [Unity 3D AudioSource] ◄── [Ring Buffer / AudioFilterRead] ◄── [Unity C# Decoder]

Key Engineering Requirements:

  1. 3D Spatial Attenuation: Setting AudioSource.spatialBlend = 1.0f so voice originates from the physical NPC's mouth position in 3D world space.
  2. Chunked WAV/PCM Decoding: Decoding 22.05kHz / 44.1kHz audio samples into float arrays without garbage collector (GC) allocations.
  3. Queue Stutter Prevention: Maintaining a small ring buffer so audio playback remains smooth even during brief network jitter.

2. Production C# Code: 3D Spatial Audio Streamer

Below is a production C# manager (AISpatialVoiceStreamer.cs) that fetches MP3/WAV audio streams and plays them dynamically through a 3D spatial AudioSource.

CSHARP
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

/// <summary>
/// Production C# Manager for handling 3D Spatial TTS Voice Streaming in Unity.
/// Downloads generated audio clips dynamically and plays them through a 3D AudioSource.
/// </summary>
public class AISpatialVoiceStreamer : MonoBehaviour
{
    [Header("Engine Component References")]
    [SerializeField] private AudioSource spatialAudioSource;

    [Header("TTS API Configuration")]
    [SerializeField] private string ttsApiUrl = "https://api.openai.com/v1/audio/speech";
    [SerializeField] private string apiKey = "YOUR_API_KEY_HERE";
    [SerializeField] private string voiceName = "alloy";

    private void Awake()
    {
        if (spatialAudioSource == null)
        {
            spatialAudioSource = GetComponent<AudioSource>();
        }

        // Enable 3D Spatial Audio (1.0 = Fully 3D, 0.0 = 2D Mono)
        if (spatialAudioSource != null)
        {
            spatialAudioSource.spatialBlend = 1.0f;
            spatialAudioSource.minDistance = 2.0f;
            spatialAudioSource.maxDistance = 20.0f;
        }
    }

    /// <summary>
    /// Converts text into speech and plays it through the 3D spatial AudioSource.
    /// </summary>
    public void SpeakTextSpatial(string textToSpeak)
    {
        if (string.IsNullOrEmpty(textToSpeak)) return;
        StartCoroutine(DownloadAndPlayTTS(textToSpeak));
    }

    private IEnumerator DownloadAndPlayTTS(string text)
    {
        string jsonBody = $"{{\"model\":\"tts-1\",\"input\":\"{text}\",\"voice\":\"{voiceName}\"}}";
        byte[] rawData = Encoding.UTF8.GetBytes(jsonBody);

        using (UnityWebRequest request = new UnityWebRequest(ttsApiUrl, "POST"))
        {
            request.uploadHandler = new UploadHandlerRaw(rawData);
            request.downloadHandler = new DownloadHandlerAudioClip(ttsApiUrl, AudioType.MPEG);
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Authorization", $"Bearer {apiKey}");

            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                AudioClip downloadedClip = DownloadHandlerAudioClip.GetContent(request);
                if (downloadedClip != null && spatialAudioSource != null)
                {
                    spatialAudioSource.clip = downloadedClip;
                    spatialAudioSource.Play();
                    Debug.Log("[AI Voice Streamer] Playing 3D Spatial Speech Clip.");
                }
            }
            else
            {
                Debug.LogError($"[AI Voice Error]: Failed to download TTS audio. Error: {request.error}");
            }
        }
    }
}

3. Masterclass Series Conclusion & Summary

Across this 3-part masterclass series, we built a complete enterprise AI NPC pipeline for Unity:

  1. Part 1: Local vs. Cloud LLM Inference: Selected the right inference runtime (ONNX/Ollama vs. OpenAI/Anthropic APIs) balancing latency and cost.
  2. Part 2: Structured JSON & Behavior Trees: Enforced strict JSON schemas to drive Unity NavMesh pathfinding and Animator state machines.
  3. Part 3: Spatial Audio & Voice Streaming: Implemented 3D spatial TTS audio streaming for dynamic character speech.

💡 Building a Custom AI Gameplay System?

Need help building low-latency spatial voice systems, optimizing LLM inference, or training custom NPC behavior models in Unity?

  • 3D Spatial Audio Pipelines: Setting up low-latency TTS streams and ring-buffer audio filters.
  • Unity AI Gameplay Engineering: Complete end-to-end integration of LLMs, behavior trees, and spatial audio.

👉 Book an AI Gameplay Systems Strategy Session or reach out directly to discuss your project requirements.


🎮 Shipped Projects & Official Store Profiles

Explore commercial titles and technical systems built with Unity across official stores:


Planning an AI-powered title? Check out our AI Gameplay Systems Services or explore our 2026 Mobile Game Development Cost Guide.

Share this article

Looking to build a production-ready game?

See how I built Bird Sort Mania in 20 days using AI, or check out my full Mobile Games Portfolio to see my shipped titles on Android and iOS.

Join 5,000+ Game Developers

Get weekly insights on Unity performance optimization, AI gameplay architectures, and robust system design. No spam, just deep technical breakdowns.

Unsubscribe at any time. Your data is never shared.

Recommended Reading

More articles in AI Gameplay