import asyncio import aiohttp import io import os from utils import normalize_audio_loudness BASE_URL = os.getenv("BASE_URL") AUDIO_URL = os.getenv("AUDIO_URL") async def generate_api(voice_ids, text): timeout = aiohttp.ClientTimeout(total=10) # 设置10秒的总超时时间 try: async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(BASE_URL+"tts", json={"ids": voice_ids, "text": text}) as response: if response.status == 200: # 读取响应内容 audio_data = await response.read() # print(type(audio_data)) # 创建一个字节流对象 audio_data = normalize_audio_loudness(audio_data) return audio_data else: print(response) return f"合成失败: {response.status}" except asyncio.TimeoutError: return "请求超时,请稍后重试" except aiohttp.ClientError as e: return f"网络错误: {str(e)}" async def get_audio(voice_id): url = AUDIO_URL + voice_id + ".ogg" try: async with aiohttp.ClientSession() as session: async with session.get(url) as response: if response.status == 200: return await response.read() else: return f"获取音频失败: {response.status}" except asyncio.TimeoutError: return "请求超时,请稍后重试" except aiohttp.ClientError as e: return f"网络错误: {str(e)}"