TTS does not work (curl, python)

Hi everyone, i’m trying the code from exaples
Curl:

curl https://api.openai.com/v1/audio/speech \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "tts-1",
    "input": "Today is a wonderful day to build something people love!",
    "voice": "alloy"
  }' \
  --output speech.mp3

% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 614 100 443 100 171 1428 551 --:–:-- --:–:-- --:–:-- 1993

but in the end getting 0 byte file

Pyton:

from pathlib import Path
from openai import OpenAI
client = OpenAI()

speech_file_path = Path(__file__).parent / "speech.mp3"
response = client.audio.speech.create(
  model="tts-1",
  voice="alloy",
  input="Today is a wonderful day to build something people love!"
)

response.stream_to_file(speech_file_path)

DeprecationWarning: Due to a bug, this method doesn’t actually stream the response content, .with_streaming_response.method() should be used instead
response.stream_to_file(speech_file_path)

Does anyone know how to solve this problems?

1 Like

Have an example that will save to the working directory

import openai

speech_file_path = "./blah.mp3"
params = {
  "model": "tts-1", "voice": "fable",
  "input": """
Why, no; for she hath broke the lute to me. I did but tell her she mistook her frets.
""".strip()
}
client = openai.Client()
try:
    response = client.audio.speech.create(**params)
    response.stream_to_file(speech_file_path)
except Exception as e:
    print(f"Error: {e}")

Unfortunately, I’ve got the same error:

DeprecationWarning: Due to a bug, this method doesn’t actually stream the response content, .with_streaming_response.method() should be used instead response.stream_to_file(speech_file_path)

checked with Python (3.11) and openAI (1.10.0) versions .
maybe I need to downgrade it somehow?

1 Like

You can ignore the warning; you get your file.

If you want a destination other than a file, you would use other API methods completely. You would need a client handler to deal with the method mentioned, iterating over chunks of streamed bytes.

Here for example is a link to a method that will actually be a generator of bytes.

It then could be “played” to a buffered stream handler for a media player, for example.

Thanks, i add couple rows to ignor this warnings:

import warnings
warnings.filterwarnings(“ignore”, category=DeprecationWarning)

and it works

3 Likes