wangzhibo
2026-10-08 220e4fab27b7f419b3e89e2f2d28ae789aac09d7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import requests
from core.providers.tts.base import TTSProviderBase
 
 
class TTSProvider(TTSProviderBase):
    TTS_PARAM_CONFIG = [
        ("ttsVolume", "gain", -10, 10, 0, int),
        ("ttsRate", "speed", 0.25, 4, 1, lambda v: round(float(v), 2)),
    ]
 
    def __init__(self, config, delete_audio_file):
        super().__init__(config, delete_audio_file)
        self.model = config.get("model")
        self.access_token = config.get("access_token")
        if config.get("private_voice"):
            self.voice = config.get("private_voice")
        else:
            self.voice = config.get("voice")
        self.audio_file_type = config.get("response_format", "mp3")
        self.speed = float(config.get("speed", 1.0))
        self.gain = config.get("gain")
 
        # 应用百分比调整(如果存在),否则使用公有化配置
        self._apply_percentage_params(config)
 
        self.host = "api.siliconflow.cn"
        self.api_url = f"https://{self.host}/v1/audio/speech"
 
    async def text_to_speak(self, text, output_file):
        request_json = {
            "model": self.model,
            "input": text,
            "voice": self.voice,
            "response_format": self.audio_file_type,
        }
        headers = {
            "Authorization": f"Bearer {self.access_token}",
            "Content-Type": "application/json",
        }
        try:
            response = requests.request(
                "POST", self.api_url, json=request_json, headers=headers,
                timeout=self.tts_timeout,
            )
            if response.status_code != 200:
                raise Exception(
                    f"{__name__} HTTP {response.status_code}: {response.text[:200]}"
                )
            data = response.content
            if output_file:
                with open(output_file, "wb") as file_to_save:
                    file_to_save.write(data)
            else:
                return data
        except Exception as e:
            raise Exception(f"{__name__} error: {e}")