我們在「【語音合成技術 - GPT-SoVITS】讓機器說人話的語音生成服務」分享了語音合成技術, 該套GPT-SoVITS也非常的出色, 但效能有點不是非常理想, 加上需要GPU才能達到較佳的體驗, 如此一來成本就會有點高了, 因此我們找了另外一套MeloTTS, 這一套強調CPU推理非常的快!
git clone <https://github.com/myshell-ai/MeloTTS.git>
cd MeloTTS
pip install -e .
python -m unidic download
奇怪了, 過程怎麼裝不成功呢? 出現這樣的訊息:
因此我們決定裝裝boto3來讓下載順利完成:
pip install boto3
當然我們也可以寫在 requirements.txt 裡面再重新安裝一次, 🤷♂️ 都可以, 取決於您的習慣。
當然這次就順利安裝完成囉! 接著我們看到官方的文件有展示Python的API使用方式:
可是我們希望架設一隻API是未來可以發展UI的接口, 這可以怎麼辦呢? 我們可以使用python的fastAPI來完成, 那麼需要安裝的套件如下:
requirements.txt
fastapi
uvicorn
numpy
接著重新安裝一次, 該有的套件就有了, 我們就可以開始準備動手撰寫API的程式碼囉! 這邊廢話不多說, 直接上Code, 如果對於Code的部份有需要理解的話, 也歡迎使用ChatGPT、Gemini、cursor…等工具來輔助我們, 讓事情更加事半功倍。
from melo.api import TTS
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
from fastapi.middleware.cors import CORSMiddleware
import numpy as np
import io
import wave
import torch
app = FastAPI()
# 設置CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 初始化TTS模型
speed = 1.0
device = 'cpu' # or cuda:0 if you have GPU
model = TTS(language='ZH', device=device)
speaker_ids = model.hps.data.spk2id
def numpy_to_wav_bytes(audio_data: np.ndarray, sample_rate: int) -> bytes:
"""將numpy數組轉換為WAV格式的字節數據"""
buffer = io.BytesIO()
with wave.open(buffer, 'wb') as wav_file:
wav_file.setnchannels(1) # 單聲道
wav_file.setsampwidth(2) # 16位
wav_file.setframerate(sample_rate)
# 確保數據在正確的範圍內並轉換為16位整數
audio_int16 = (audio_data * 32767).astype(np.int16)
wav_file.writeframes(audio_int16.tobytes())
return buffer.getvalue()
@app.get("/tts")
async def text_to_speech(text: str):
try:
# model.tts_to_file 改為 model.tts,直接獲取音頻數據
audio_data = model.tts_to_file(text, speaker_ids['ZH'], speed=speed)
# 使用 numpy_to_wav_bytes 函數將音頻數據轉換為 WAV 格式
wav_bytes = numpy_to_wav_bytes(audio_data, sample_rate=model.hps.data.sampling_rate)
return Response(wav_bytes, media_type="audio/wav")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=9881)
API寫好之後, 我們就準備啟用它。
python tts_api.py
使用API推理試試看!
http://localhost:9881/tts?text=在遙遠的山谷中清澈的溪水流淌樹影搖曳鳥兒自由地飛翔帶來了春天
TTS如雨後春筍般的出現,我們要學會如何從中挑出我們真正需要的那一個系統與模型, 而這邊僅是分享一些在實際安裝或者使用這的問題, 如果對於一系列文章有興趣的朋友也歡迎下方留言, 浪我們更完整的去認識這些TTS的技術。