From 59c2deaadc9042a3569766c90160e96bc2b61393 Mon Sep 17 00:00:00 2001 From: Chris <119588753+Chris-websketch@users.noreply.github.com> Date: Fri, 7 Mar 2025 10:32:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Eopenai=20tts=20(#137)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On branch openai_tts Changes to be committed: modified: config.yaml new file: core/providers/tts/openai_tts.py Co-authored-by: 欣南科技 --- config.yaml | 15 ++++++++++++- core/providers/tts/openai_tts.py | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 core/providers/tts/openai_tts.py diff --git a/config.yaml b/config.yaml index ce065b175..f937f28d2 100644 --- a/config.yaml +++ b/config.yaml @@ -307,9 +307,22 @@ TTS: # volume: 50 # speech_rate: 0 # pitch_rate: 0 + OpenAITTS: + # openai官方文本转语音服务,可支持全球大多数语种 + type: openai_tts + api_key: 你的openai api key + # 国内需要使用代理 + api_url: https://api.openai.com/v1/audio/speech + # 可选tts-1或tts-1-hd,tts-1速度更快tts-1-hd质量更好 + model: tts-1 + # 演讲者,可选alloy, echo, fable, onyx, nova, shimmer + voice: alloy + # 语速范围0.25-4.0 + speed: 1 + output_file: tmp/ + TTS302AI: # 添加 302.ai TTS 配置 # token申请地址:https://dash.302.ai/ - TTS302AI: # 302AI语音合成服务,需要先在302平台创建账户充值,并获取密钥信息 # 获取api_keyn路径:https://dash.302.ai/apis/list # 价格,$35/百万字符。火山原版¥450元/万字符 diff --git a/core/providers/tts/openai_tts.py b/core/providers/tts/openai_tts.py new file mode 100644 index 000000000..db60d3d90 --- /dev/null +++ b/core/providers/tts/openai_tts.py @@ -0,0 +1,38 @@ +import os +import uuid +import requests +from datetime import datetime +from core.providers.tts.base import TTSProviderBase + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.api_key = config.get("api_key") + self.api_url = config.get("api_url", "https://api.openai.com/v1/audio/speech") + self.model = config.get("model", "tts-1") + self.voice = config.get("voice", "alloy") + self.response_format = "wav" + self.speed = config.get("speed", 1.0) + self.output_file = config.get("output_file", "tmp/") + + def generate_filename(self, extension=".wav"): + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") + + async def text_to_speak(self, text, output_file): + headers = { + "Authorization": f"Bearer {self.api_key}", + "Content-Type": "application/json" + } + data = { + "model": self.model, + "input": text, + "voice": self.voice, + "response_format": "wav", + "speed": self.speed + } + response = requests.post(self.api_url, json=data, headers=headers) + if response.status_code == 200: + with open(output_file, "wb") as audio_file: + audio_file.write(response.content) + else: + raise Exception(f"OpenAI TTS请求失败: {response.status_code} - {response.text}") \ No newline at end of file