- android-engine:TextToSpeechService 引擎,含设置页、语音包导入(SHA-256 校验)与预热 - server:Go CPU 合成服务与部署文件 - test-client:端到端验证客户端 - 模型与语音包不入库,见 models/README.md
107 lines
2.4 KiB
Go
107 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"sync"
|
|
"time"
|
|
|
|
sherpa "github.com/k2-fsa/sherpa-onnx-go/v2/sherpa_onnx"
|
|
|
|
"tts-server/internal/tts"
|
|
)
|
|
|
|
// engine keeps at most one voice model loaded (the 512MB server cannot hold
|
|
// two), serializes synthesis and reloads only when the requested voice changes.
|
|
type engine struct {
|
|
mu sync.Mutex
|
|
threads int
|
|
tts *sherpa.OfflineTts
|
|
loaded string
|
|
}
|
|
|
|
func newEngine(threads int) *engine {
|
|
return &engine{threads: threads}
|
|
}
|
|
|
|
func (e *engine) preload(pack *tts.VoicePack) error {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
_, err := e.obtain(pack)
|
|
return err
|
|
}
|
|
|
|
func (e *engine) synthesize(pack *tts.VoicePack, text string, speed, pitch float32) ([]float32, int, error) {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
|
|
model, err := e.obtain(pack)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
// Same generation config as Synthesizer.java: silenceScale 0, sid, speed,
|
|
// numSteps 5.
|
|
cfg := &sherpa.GenerationConfig{SilenceScale: 0, Speed: speed, Sid: pack.SpeakerID, NumSteps: 5}
|
|
audio := model.GenerateWithConfig(text, cfg, nil)
|
|
if audio == nil || len(audio.Samples) == 0 {
|
|
return nil, 0, errors.New("synthesis produced no audio")
|
|
}
|
|
|
|
samples := audio.Samples
|
|
if tts.PitchShiftNeeded(pitch) {
|
|
samples = tts.ShiftPitch(samples, pitch)
|
|
}
|
|
return samples, audio.SampleRate, nil
|
|
}
|
|
|
|
func (e *engine) close() {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
e.release()
|
|
}
|
|
|
|
func (e *engine) obtain(pack *tts.VoicePack) (*sherpa.OfflineTts, error) {
|
|
if e.tts != nil && e.loaded == pack.Name {
|
|
return e.tts, nil
|
|
}
|
|
e.release()
|
|
|
|
cfg := &sherpa.OfflineTtsConfig{
|
|
Model: sherpa.OfflineTtsModelConfig{
|
|
Vits: sherpa.OfflineTtsVitsModelConfig{
|
|
Model: pack.ModelPath,
|
|
Lexicon: pack.LexiconPath,
|
|
Tokens: pack.TokensPath,
|
|
DataDir: pack.DataDir,
|
|
},
|
|
NumThreads: e.threads,
|
|
Debug: 0,
|
|
Provider: "cpu",
|
|
},
|
|
RuleFsts: pack.RuleFsts,
|
|
RuleFars: "",
|
|
MaxNumSentences: 1,
|
|
SilenceScale: 0.2,
|
|
}
|
|
|
|
start := time.Now()
|
|
model := sherpa.NewOfflineTts(cfg)
|
|
if model == nil {
|
|
return nil, fmt.Errorf("load voice %q failed", pack.Name)
|
|
}
|
|
e.tts = model
|
|
e.loaded = pack.Name
|
|
log.Printf("voice %s loaded: sample rate %d, took %s",
|
|
pack.Name, model.SampleRate(), time.Since(start).Round(time.Millisecond))
|
|
return model, nil
|
|
}
|
|
|
|
func (e *engine) release() {
|
|
if e.tts != nil {
|
|
sherpa.DeleteOfflineTts(e.tts)
|
|
e.tts = nil
|
|
e.loaded = ""
|
|
}
|
|
} |