I'm using the OpenAI Python library to generate audio content from text. However, I need to process and return the audio content directly without storing it in a local file. How can I achieve this using the OpenAI library? I've thought of streaming the audio content to an in-memory buffer, but I'm encountering issues with decoding the audio content. Any guidance on how to properly handle and return the audio content in memory would be greatly appreciated.
This is the code am using,
import io
import requests
import logging
import json
from pathlib import Path
from openai import OpenAI
class AudioGenerator:
logger = logging.getLogger(name)
Код: Выделить всё
@staticmethod
def generate_audio(text, api_key):
client = OpenAI(api_key=api_key)
speech_file_path = Path(__file__).parent/"speech.mp3"
print(text)
try:
response = client.audio.speech.create(
model="tts-1",
voice="alloy",
input=text
)
response.stream_to_file(speech_file_path)
content_type = response.headers.get("Content-Type")
if content_type != "audio/mpeg":
raise ValueError(f"Unexpected content type in response: {content_type}")
AudioGenerator.logger.info('Audio generated successfully!')
return response.content
except requests.exceptions.RequestException as e:
AudioGenerator.logger.error("Error making API request:", exc_info=e)
raise
except json.JSONDecodeError as e:
AudioGenerator.logger.error("Error parsing API response:", exc_info=e)
raise
except Exception as e: # Catch any other unexpected exceptions
AudioGenerator.logger.error("Unexpected error:", exc_info=e)
raise
Источник: https://stackoverflow.com/questions/781 ... using-open