Issues with streaming audio
I'm having some trouble trying to stream the audio output from the server. It's seems like it doesn't send the audio data until the audio is fully generated, resulting in a long pause. I've attached the quick test script I'm using to test response times for both APIs.
#!/usr/bin/env python3
"""
Test Chatterbox's custom /tts endpoint for TRUE streaming capability
"""
import requests
import time
import json
def test_custom_tts_streaming():
"""Test if /tts endpoint actually streams in real-time"""
url = "http://localhost:8004/tts"
headers = {
"Content-Type": "application/json"
}
payload = {
"text": "This is a long test sentence to see if the custom TTS endpoint streams audio in real-time chunks as the audio is being generated, rather than waiting until the entire audio is complete. We want to see if chunks arrive progressively during generation, not all at once after a long delay.",
"voice_mode": "predefined",
"predefined_voice_id": "Emily.wav",
"output_format": "wav",
"split_text": False, # Don't split text to get pure streaming behavior
"temperature": 0.7,
"speed_factor": 1.0
}
print("π§ͺ Testing Chatterbox Custom /tts Endpoint for TRUE Streaming")
print("="*60)
print(f"URL: {url}")
print(f"Payload: {json.dumps(payload, indent=2)}")
print("\n" + "="*60)
start_time = time.time()
first_chunk_time = None
chunk_count = 0
chunk_times = []
total_bytes = 0
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=120) as response:
print(f"β±οΈ Request sent at: {start_time:.3f}")
print(f"π‘ Response status: {response.status_code}")
print(f"π Response headers: {dict(response.headers)}")
if response.status_code != 200:
print(f"β Error: {response.status_code}")
print(f"Response text: {response.text}")
return
print(f"\nπ Receiving chunks from CUSTOM /tts endpoint...")
print("Chunk# | Time Since Start | Chunk Size | Time Between | Cumulative")
print("-" * 70)
last_chunk_time = start_time
for chunk in response.iter_content(chunk_size=8192): # 8KB chunks
if chunk:
chunk_count += 1
current_time = time.time()
total_bytes += len(chunk)
if first_chunk_time is None:
first_chunk_time = current_time
time_to_first = current_time - start_time
print(f"π FIRST CHUNK from /tts after {time_to_first:.3f}s")
time_since_start = current_time - start_time
time_between = current_time - last_chunk_time
print(f"{chunk_count:5d} | {time_since_start:13.3f}s | {len(chunk):9d}B | {time_between:8.3f}s | {total_bytes:8d}B")
chunk_times.append(time_since_start)
last_chunk_time = current_time
# Show first 15 chunks for analysis
if chunk_count >= 15:
print(f"... (showing first {chunk_count} chunks)")
break
total_time = time.time() - start_time
print(f"\nπ CUSTOM /tts ENDPOINT RESULTS:")
print(f" Total chunks received: {chunk_count}")
print(f" Total bytes: {total_bytes}")
print(f" Time to first chunk: {time_to_first:.3f}s")
print(f" Total time: {total_time:.3f}s")
# Analyze streaming behavior
if time_to_first < 1.0:
print(f" β
FAST first chunk suggests TRUE STREAMING capability!")
elif time_to_first < 2.0:
print(f" β‘ Moderate delay - possible streaming with initial processing")
else:
print(f" π¨ Large delay suggests this endpoint also pre-generates")
# Check chunk timing pattern for TRUE streaming
if len(chunk_times) > 3:
gaps = [chunk_times[i] - chunk_times[i-1] for i in range(1, len(chunk_times))]
avg_gap = sum(gaps) / len(gaps)
# For TRUE streaming, we expect more variable timing
instant_chunks = sum(1 for gap in gaps if gap < 0.05) # < 50ms
total_gaps = len(gaps)
instant_ratio = instant_chunks / total_gaps
print(f" π Average time between chunks: {avg_gap:.3f}s")
print(f" π Instant chunks ratio: {instant_ratio:.2%} ({instant_chunks}/{total_gaps})")
if instant_ratio > 0.8: # More than 80% instant
print(f" π¨ HIGH instant ratio - likely BATCH TRANSFER")
print(f" π Server probably generates complete audio first")
else:
print(f" β
VARIABLE timing suggests TRUE STREAMING!")
print(f" π― This endpoint appears to stream during generation")
except Exception as e:
print(f"β Error during custom /tts test: {e}")
import traceback
traceback.print_exc()
def compare_endpoints():
"""Quick comparison test between both endpoints"""
print(f"\nπ QUICK COMPARISON TEST")
print("="*40)
test_text = "Short test for comparison."
endpoints = [
{
"name": "OpenAI Compatible",
"url": "http://localhost:8004/v1/audio/speech",
"headers": {"Authorization": "Bearer local-key", "Content-Type": "application/json"},
"payload": {
"model": "tts-1",
"input": test_text,
"voice": "Emily.wav",
"response_format": "wav"
}
},
{
"name": "Custom /tts",
"url": "http://localhost:8004/tts",
"headers": {"Content-Type": "application/json"},
"payload": {
"text": test_text,
"voice_mode": "predefined",
"predefined_voice_id": "Emily.wav",
"output_format": "wav"
}
}
]
for endpoint in endpoints:
print(f"\nπ§ͺ Testing {endpoint['name']}...")
start = time.time()
try:
response = requests.post(
endpoint['url'],
headers=endpoint['headers'],
json=endpoint['payload'],
stream=True,
timeout=30
)
first_chunk = next(response.iter_content(chunk_size=1024), None)
first_chunk_time = time.time() - start
print(f" β±οΈ Time to first chunk: {first_chunk_time:.3f}s")
print(f" π‘ Status: {response.status_code}")
if first_chunk_time < 1.0:
print(f" β
FAST - Likely supports streaming")
else:
print(f" π¨ SLOW - Likely pre-generates audio")
except Exception as e:
print(f" β Error: {e}")
if __name__ == "__main__":
print("π§ͺ CHATTERBOX CUSTOM API STREAMING TEST")
print("="*50)
# Test the custom /tts endpoint thoroughly
test_custom_tts_streaming()
# Quick comparison between endpoints
compare_endpoints()
print(f"\nπ― CONCLUSIONS:")
print(f" β’ OpenAI /v1/audio/speech = Pre-generate + chunked transfer")
print(f" β’ Custom /tts = ? (testing will reveal)")
print(f" β’ If /tts shows TRUE streaming β implement custom API client")
Is proper streaming supported? Any help would be appreciated!
Streaming is not supported. The server needs to generate the full audio before returning it to the client. However, the way to accomplish this is by processing smaller text chunks and pulling audio for each chunk from the /tts endpoint, then playing them continuously. That gets you pretty close to a streaming experience.
Streaming is not supported. The server needs to generate the full audio before returning it to the client. However, the way to accomplish this is by processing smaller text chunks and pulling audio for each chunk from the /tts endpoint, then playing them continuously. That gets you pretty close to a streaming experience.
Do you think that this would negatively impact the overall "performance" of the reading?
Streaming is not supported. The server needs to generate the full audio before returning it to the client. However, the way to accomplish this is by processing smaller text chunks and pulling audio for each chunk from the /tts endpoint, then playing them continuously. That gets you pretty close to a streaming experience.
Do you think that this would negatively impact the overall "performance" of the reading?
Not at all. Just combine all chunks and play them sequentially. As long as the generation is faster than reading the speech should sound natural.
It definitely works, but it seems like the tone can shift in weird ways at times. I am not sure if that is a model, settings, or an implementation issue.
I appreciate you getting back to me!
Try using the recommended settings and a fixed seed with the /TTS api endpoint for all chunks. For example:
Cfg: 0.5 Exaggeration: 0.5 Temperature: 0.8 Seed: 100
any plans to allow for the streaming to happen on the frontend? that would be much better than only through the API.
Streaming would also have to depend on how good oneβs hardware is. Even with a RTX 4090, it takes time to generate even a few sentences.
@Mushy-Snugglebites-badonkadonk "Even with a RTX 4090, it takes time to generate even a few sentences." What realtime factor (RTF) do you suspect?