Streaming allows you to receive audio chunks in real-time as they’re generated, enabling immediate playback without waiting for the entire audio file to be created. This is essential for interactive applications like voice assistants and chatbots.
import { SixtyDBClient } from '60db';const client = new SixtyDBClient('your-api-key');// Audio player setupconst audioContext = new AudioContext();const audioQueue = [];await client.textToSpeechStream( { text: 'This is a longer text that will be streamed in real-time for immediate playback.', voice_id: 'default-voice' }, { onChunk: async (chunk) => { // Convert chunk to audio buffer const audioBuffer = await audioContext.decodeAudioData(chunk.buffer); // Add to queue and play audioQueue.push(audioBuffer); if (audioQueue.length === 1) { playNextChunk(); } }, onComplete: () => { console.log('Streaming complete'); }, onError: (error) => { console.error('Streaming error:', error); } });function playNextChunk() { if (audioQueue.length === 0) return; const buffer = audioQueue[0]; const source = audioContext.createBufferSource(); source.buffer = buffer; source.connect(audioContext.destination); source.onended = () => { audioQueue.shift(); playNextChunk(); }; source.start();}
from sixtydb import SixtyDBClientimport pyaudioclient = SixtyDBClient('your-api-key')# Audio player setupp = pyaudio.PyAudio()stream = p.open( format=pyaudio.paInt16, channels=1, rate=24000, output=True)def handle_chunk(chunk): # Play audio chunk immediately stream.write(chunk)def handle_complete(): print("Streaming complete") stream.stop_stream() stream.close() p.terminate()def handle_error(error): print(f"Error: {error}")# Stream text to speechclient.text_to_speech_stream( text='This is a longer text that will be streamed in real-time.', on_chunk=handle_chunk, on_complete=handle_complete, on_error=handle_error, voice_id='default-voice')