Stream text to speech with Unreal Speech in Python

Receive speech synthesis progressively in Python, save it as MP3 and check the result.

Updated 5 min

What you will create

Receive short speech synthesis bytes progressively in Python and save them as an MP3 file. This example uses the current v8 endpoint. It does not include live audio playback: receiving a stream and playing it during reception are separate steps.

Before you start

Prepare Python with requests available, an authorised Unreal Speech key and a voice ID compatible with your v8 access. Load the key into UNREAL_SPEECH_API_KEY and the voice into UNREAL_SPEECH_VOICE_ID through your secure local environment. Never place a key in a webpage, screenshot or shared repository. Check costs before running: this script actually sends text to the provider and may consume credits.

Step-by-step

  1. Prepare non-confidential text. Start with one English sentence and a suitable voice. The short endpoint accepts up to 1,000 characters; do not send an entire document.
  2. Prepare the output folder. Check that sample.mp3 does not already exist. Exclusive file creation protects an earlier result instead of overwriting it.
  3. Review the request. Authentication goes in the Bearer header, content in Text and the voice in VoiceId. The codec is explicitly MP3. Do not mix v7 and v8 examples.
  4. Run once after checking costs. The HTTP status is checked before writing. Received chunks are appended to the file; an exception stops the script rather than automatically retrying a potentially billable request.
  5. Listen after completion. Open the MP3 in a compatible player and compare the spoken sentence with the text. File existence alone does not establish successful synthesis.

Example to adapt

Reference example to review before running. Syntax was checked locally, but no API request or audio listening test was performed.

import os
from pathlib import Path
import requests

text = "The reading workshop starts at ten. Bring one notebook."
if not text.strip() or len(text) > 1000:
    raise ValueError("Use 1 to 1000 characters")

key = os.environ["UNREAL_SPEECH_API_KEY"]
voice = os.environ["UNREAL_SPEECH_VOICE_ID"]
if not key.strip() or not voice.strip():
    raise ValueError("Missing key or voice ID")

target = Path("sample.mp3")
if target.exists():
    raise FileExistsError("Choose another output filename")

with requests.post(
    "https://api.v8.unrealspeech.com/stream",
    headers={"Authorization": f"Bearer {key}"},
    json={"Text": text, "VoiceId": voice, "Codec": "libmp3lame"},
    stream=True,
    timeout=(10, 60),
) as response:
    response.raise_for_status()
    content_type = response.headers.get("Content-Type", "").lower()
    if "json" in content_type or "text/" in content_type:
        raise RuntimeError("Unexpected response type")
    with target.open("xb") as output:
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:
                output.write(chunk)

Check your result

  • The final sentence is complete and “ten” and “one notebook” are intelligible.
  • The file contains playable audio rather than an error message.
  • Logs contain neither the key nor the authentication header.
  • Empty text is rejected before any request.

Common problems

Missing variable: configure the environment without printing the secret. HTTP error: check permissions, credits and parameters in your account; do not repeatedly retry. Reception interrupted: a partial file may remain. Keep it separately for diagnosis or deliberately remove it before an authorised new attempt. Unexpected response type: the simple check above is not complete audio format validation. A binary response can still be unusable.

Next steps

Add an MP3-compatible player if your project needs progressive playback, including cancellation and error handling. This example guarantees no fixed latency. Review the Unreal Speech profile before integrating the service into an application.