mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
feat: add tts
This commit is contained in:
parent
0c74043d3d
commit
090b68cf20
3 changed files with 101 additions and 3 deletions
|
|
@ -179,6 +179,7 @@ ASR:
|
||||||
dev_pid: 1536
|
dev_pid: 1536
|
||||||
api_key: 你的星河社区账户令牌
|
api_key: 你的星河社区账户令牌
|
||||||
secret_key: 你的星河社区账户令牌
|
secret_key: 你的星河社区账户令牌
|
||||||
|
output_dir: tmp/
|
||||||
FunASR:
|
FunASR:
|
||||||
type: fun_local
|
type: fun_local
|
||||||
model_dir: models/SenseVoiceSmall
|
model_dir: models/SenseVoiceSmall
|
||||||
|
|
@ -583,6 +584,12 @@ TTS:
|
||||||
# Authorization: Bearer xxxx
|
# Authorization: Bearer xxxx
|
||||||
format: wav # 接口返回的音频格式
|
format: wav # 接口返回的音频格式
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
|
AistudioTTS:
|
||||||
|
# 自定义的音频文件路径
|
||||||
|
type: aistudio
|
||||||
|
output_dir: tmp/
|
||||||
|
api_key: 你的星河社区账户令牌
|
||||||
|
secret_key: 你的星河社区账户令牌
|
||||||
# 模块测试配置
|
# 模块测试配置
|
||||||
module_test:
|
module_test:
|
||||||
test_sentences: # 自定义测试语句
|
test_sentences: # 自定义测试语句
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.scope = config.get("scope")
|
self.scope = config.get("scope")
|
||||||
self.dev_pid = config.get("dev_pid")
|
self.dev_pid = config.get("dev_pid")
|
||||||
self.output_dir = config.get("output_dir")
|
self.output_dir = config.get("output_dir")
|
||||||
|
self.cuid = "123456PYTHON"
|
||||||
|
|
||||||
self.asr_url = "http://vop.baidu.com/server_api"
|
self.asr_url = "http://vop.baidu.com/server_api"
|
||||||
self.token = self.fetch_token(config.get("api_key"), config.get("secret_key"))
|
self.token = self.fetch_token(config.get("api_key"), config.get("secret_key"))
|
||||||
|
|
@ -82,7 +83,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
return b"".join(pcm_data)
|
return b"".join(pcm_data)
|
||||||
|
|
||||||
def _build_request_body(self, file_format: str = "wav") -> tuple[dict, dict]:
|
def _build_request_body(self, file_format: str = "wav", rate: int = 16000) -> tuple[dict, dict]:
|
||||||
params = {
|
params = {
|
||||||
'cuid': self.cuid,
|
'cuid': self.cuid,
|
||||||
'token': self.token,
|
'token': self.token,
|
||||||
|
|
@ -90,7 +91,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
}
|
}
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
'Content-Type': f'audio/{file_format}; rate={self.rate}'
|
'Content-Type': f'audio/{file_format}; rate={rate}'
|
||||||
}
|
}
|
||||||
return params, headers
|
return params, headers
|
||||||
|
|
||||||
|
|
@ -103,7 +104,9 @@ class ASRProvider(ASRProviderBase):
|
||||||
timeout=10 # 设置超时时间
|
timeout=10 # 设置超时时间
|
||||||
)
|
)
|
||||||
response.raise_for_status() # 检查HTTP错误
|
response.raise_for_status() # 检查HTTP错误
|
||||||
return response.json()
|
if response.json().get("result", None) is None:
|
||||||
|
raise RuntimeError("语音识别失败,结果为空!")
|
||||||
|
return "".join(response.json().get("result", None))
|
||||||
|
|
||||||
async def speech_to_text(self, opus_data: list[bytes], session_id: str) -> list[str | None, str | None]:
|
async def speech_to_text(self, opus_data: list[bytes], session_id: str) -> list[str | None, str | None]:
|
||||||
"""将语音数据转换为文本"""
|
"""将语音数据转换为文本"""
|
||||||
|
|
|
||||||
88
main/xiaozhi-server/core/providers/tts/aistudio.py
Normal file
88
main/xiaozhi-server/core/providers/tts/aistudio.py
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
from functools import lru_cache
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
import json
|
||||||
|
import base64
|
||||||
|
import requests
|
||||||
|
from datetime import datetime
|
||||||
|
from core.providers.tts.base import TTSProviderBase
|
||||||
|
from urllib.parse import quote
|
||||||
|
import wave
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def gen_text_auto(text: str, tts_url: str, access_token: str, **kwargs) -> bytes:
|
||||||
|
default_params = {
|
||||||
|
"tex": text,
|
||||||
|
"tok": access_token,
|
||||||
|
"cuid": "yvON5IRqAdXhh6IFtZ5QF1nxbi4bv32Y", # 默认 CUID
|
||||||
|
"ctp": 1, # 客户端类型
|
||||||
|
"lan": "zh", # 语言类型,中文
|
||||||
|
"spd": 5, # 语速
|
||||||
|
"pit": 5, # 音调
|
||||||
|
"vol": 5, # 音量
|
||||||
|
"per": 1, # 发音人
|
||||||
|
"aue": 6 # 音频编码格式 wav
|
||||||
|
}
|
||||||
|
# 更新默认参数
|
||||||
|
default_params.update(kwargs)
|
||||||
|
|
||||||
|
# 特殊处理tex参数,需要进行两次URL编码
|
||||||
|
# 先对tex参数进行一次URL编码(httpx会自动进行第二次编码)
|
||||||
|
default_params["tex"] = quote(default_params["tex"])
|
||||||
|
|
||||||
|
# 发送 POST 请求
|
||||||
|
headers = {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
'Accept': '*/*'
|
||||||
|
}
|
||||||
|
response = requests.post(tts_url, headers=headers, data=default_params)
|
||||||
|
response.raise_for_status() # 检查HTTP错误
|
||||||
|
return response.content # 返回音频内容
|
||||||
|
|
||||||
|
class TTSProvider(TTSProviderBase):
|
||||||
|
def __init__(self, config, delete_audio_file):
|
||||||
|
super().__init__(config, delete_audio_file)
|
||||||
|
self.tts_url = "https://tsn.baidu.com/text2audio"
|
||||||
|
self.token_url = "https://aip.baidubce.com/oauth/2.0/token"
|
||||||
|
self.access_token = self.get_access_token(config.get("api_key"), config.get("secret_key"))
|
||||||
|
|
||||||
|
def get_access_token(self, api_key: str, secret_key: str) -> str | None:
|
||||||
|
"""
|
||||||
|
使用 AK,SK 生成鉴权签名(Access Token)
|
||||||
|
:return: access_token,或是 None(如果错误)
|
||||||
|
"""
|
||||||
|
params = {
|
||||||
|
"grant_type": "client_credentials",
|
||||||
|
"client_id": api_key,
|
||||||
|
"client_secret": secret_key
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
response = requests.post(self.token_url, params=params, timeout=10)
|
||||||
|
response.raise_for_status() # 检查HTTP错误
|
||||||
|
token_response = response.json() # 直接解析为JSON字典
|
||||||
|
return token_response.get("access_token")
|
||||||
|
except requests.RequestException as e:
|
||||||
|
print("Failed to get access token:", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
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):
|
||||||
|
if not text:
|
||||||
|
raise ValueError("Text cannot be empty")
|
||||||
|
if not self.access_token:
|
||||||
|
raise ValueError("Access token is not available")
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = gen_text_auto(text, self.tts_url, self.access_token)
|
||||||
|
if resp is not None and len(resp) > 0:
|
||||||
|
with wave.open(output_file, 'wb') as wf:
|
||||||
|
wf.setnchannels(1) # Mono
|
||||||
|
wf.setsampwidth(2) # 16-bit PCM
|
||||||
|
wf.setframerate(16000) # rate
|
||||||
|
wf.writeframes(resp)
|
||||||
|
else:
|
||||||
|
raise Exception(f"{__name__} response is empty or invalid")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"{__name__} error: {e}")
|
||||||
Loading…
Reference in a new issue