You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何播放Web请求返回的音频流?TTS API流无需存盘播放

Awesome question! Streaming audio directly from a TTS API without saving to local disk is totally feasible, and the approach depends on what language/environment you're working with. Let's break down solutions for the most common scenarios:


Python (Desktop/Server)

Two solid options here—using pygame for simplicity, or pyaudio for more control over the audio stream.

Option 1: Requests + Pygame

This is the quickest setup for basic playback:
First install dependencies:

pip install requests pygame

Then the code:

import requests
import pygame

# Initialize pygame's audio mixer
pygame.mixer.init()

# Replace with your actual TTS API endpoint and payload
tts_api_url = "https://your-tts-service.com/api/generate"
text_payload = {"text": "Hey there! This audio is streamed directly from a TTS API, no local files involved."}

# Stream the response instead of downloading the whole file
with requests.post(tts_api_url, json=text_payload, stream=True) as api_response:
    api_response.raise_for_status()  # Fail fast if the API returns an error
    # Load the raw stream into pygame and play
    pygame.mixer.music.load(api_response.raw)
    pygame.mixer.music.play()
    # Wait until playback finishes before exiting
    while pygame.mixer.music.get_busy():
        pygame.time.Clock().tick(10)

Option 2: Requests + PyAudio

Great if you need more control over audio parameters (like adjusting sample rate/channels):
Install dependencies first:

pip install requests pyaudio

Code example:

import requests
import pyaudio

# Configure PyAudio to match your TTS API's output format (check API docs!)
audio_player = pyaudio.PyAudio()
playback_stream = audio_player.open(
    format=pyaudio.paInt16,
    channels=1,
    rate=22050,
    output=True
)

tts_api_url = "https://your-tts-service.com/api/generate"
text_payload = {"text": "Using PyAudio for more granular streaming control."}

with requests.post(tts_api_url, json=text_payload, stream=True) as api_response:
    api_response.raise_for_status()
    # Read audio in chunks and play immediately
    for chunk in api_response.iter_content(chunk_size=1024):
        if chunk:  # Skip empty chunks
            playback_stream.write(chunk)

# Clean up resources after playback
playback_stream.stop_stream()
playback_stream.close()
audio_player.terminate()

Browser JavaScript

For web apps, you can use the Fetch API along with the Web Audio API or native <audio> element.

Basic Stream Playback (Wait for full audio)

Simple approach if you don't need real-time streaming:

async function playStreamedTTS() {
    const ttsApiUrl = "https://your-tts-service.com/api/generate";
    const requestBody = JSON.stringify({ text: "Browser-based streamed audio!" });

    try {
        const apiResponse = await fetch(ttsApiUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: requestBody
        });

        if (!apiResponse.ok) throw new Error(`API Error: ${apiResponse.status}`);

        // Convert the response to a blob and create a temporary URL
        const audioBlob = await apiResponse.blob();
        const tempAudioUrl = URL.createObjectURL(audioBlob);
        
        const audioElement = new Audio(tempAudioUrl);
        await audioElement.play();
        
        // Clean up the temporary URL once playback ends
        audioElement.onended = () => URL.revokeObjectURL(tempAudioUrl);
    } catch (error) {
        console.error("Playback failed:", error);
    }
}

// Trigger playback
playStreamedTTS();

Real-Time Streaming (Play as chunks arrive)

If your TTS API supports chunked responses (uses Transfer-Encoding: chunked), you can play audio as it comes in:

async function playRealTimeStreamedTTS() {
    const ttsApiUrl = "https://your-tts-service.com/api/generate-stream";
    const requestBody = JSON.stringify({ text: "Real-time streaming TTS in the browser!" });

    try {
        const apiResponse = await fetch(ttsApiUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: requestBody
        });

        if (!apiResponse.ok) throw new Error(`API Error: ${apiResponse.status}`);

        const audioContext = new AudioContext();
        const reader = apiResponse.body.getReader();

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            // Decode the audio chunk and play it
            const audioBuffer = await audioContext.decodeAudioData(value.buffer);
            const bufferSource = audioContext.createBufferSource();
            bufferSource.buffer = audioBuffer;
            bufferSource.connect(audioContext.destination);
            bufferSource.start();

            // Wait for this chunk to finish before playing the next
            await new Promise(resolve => bufferSource.onended = resolve);
        }
    } catch (error) {
        console.error("Real-time playback failed:", error);
    }
}

playRealTimeStreamedTTS();

Node.js

For server-side or desktop Node.js apps, use axios to stream the response and speaker to play the audio:
First install packages:

npm install axios speaker

Code example:

const axios = require('axios');
const Speaker = require('speaker');

const ttsApiUrl = "https://your-tts-service.com/api/generate";
const textPayload = { text: "Node.js streaming TTS audio without local files!" };

axios.post(ttsApiUrl, textPayload, { responseType: 'stream' })
    .then(apiResponse => {
        // Configure Speaker to match your API's audio format
        const audioSpeaker = new Speaker({
            channels: 1,
            bitDepth: 16,
            sampleRate: 22050
        });

        // Pipe the API stream directly to the speaker
        apiResponse.data.pipe(audioSpeaker);

        audioSpeaker.on('close', () => {
            console.log("Playback completed successfully!");
        });
    })
    .catch(error => {
        console.error("Error streaming audio:", error);
    });

Key Notes:

  • Always use streaming mode (stream=True in Python, responseType: 'stream' in Node.js) to avoid loading the entire audio file into memory.
  • Double-check that your playback library's audio parameters (sample rate, channels, bit depth) match what the TTS API returns—mismatched settings will cause distorted audio.
  • For real-time streaming, your TTS API must support chunked transfer encoding (most modern TTS APIs do, but verify in their docs).

内容的提问来源于stack exchange,提问作者Brian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:34:19