初始化 TTS 引擎工程:Android 系统引擎、Go 在线合成服务与测试客户端

- android-engine:TextToSpeechService 引擎,含设置页、语音包导入(SHA-256 校验)与预热
- server:Go CPU 合成服务与部署文件
- test-client:端到端验证客户端
- 模型与语音包不入库,见 models/README.md
This commit is contained in:
tongtong committed 2026-11-23 14:59:46 +08:00
commit 1856de97bc
62 files changed
+3787

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
package tts
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"math"
"os"
"path/filepath"
)
type Cache struct {
dir string
}
func NewCache(dir string) (*Cache, error) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, fmt.Errorf("create cache dir: %w", err)
}
return &Cache{dir: dir}, nil
}
// Key covers everything that changes the rendered audio, including the voice
// pack version, so upgrades invalidate old files on their own.
func (c *Cache) Key(version, voice string, speed, pitch float32, text string) string {
sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%08x\x00%08x\x00%s",
version, voice, math.Float32bits(speed), math.Float32bits(pitch), text)))
return hex.EncodeToString(sum[:])
}
func (c *Cache) Get(key string) ([]byte, bool) {
data, err := os.ReadFile(filepath.Join(c.dir, key+".wav"))
if err != nil {
return nil, false
}
return data, true
}
func (c *Cache) Put(key string, data []byte) error {
tmp, err := os.CreateTemp(c.dir, key[:8]+"-*.tmp")
if err != nil {
return err
}
name := tmp.Name()
if _, err := tmp.Write(data); err != nil {
tmp.Close()
os.Remove(name)
return err
}
if err := tmp.Close(); err != nil {
os.Remove(name)
return err
}
return os.Rename(name, filepath.Join(c.dir, key+".wav"))
}
+27
View File
@@ -0,0 +1,27 @@
package tts
import "testing"
func TestCacheRoundTrip(t *testing.T) {
c, err := NewCache(t.TempDir())
if err != nil {
t.Fatal(err)
}
key := c.Key("dev-1", "a", 1, 1.2, "你好")
if other := c.Key("dev-1", "a", 1, 1.2, "你好 "); other == key {
t.Fatal("different text produced the same key")
}
if other := c.Key("dev-2", "a", 1, 1.2, "你好"); other == key {
t.Fatal("version must be part of the key")
}
if _, ok := c.Get(key); ok {
t.Fatal("unexpected cache hit")
}
if err := c.Put(key, []byte("wav")); err != nil {
t.Fatal(err)
}
got, ok := c.Get(key)
if !ok || string(got) != "wav" {
t.Fatalf("cache get: %q %v", got, ok)
}
}
+109
View File
@@ -0,0 +1,109 @@
package tts
import "math"
// Pitch shifting without changing duration: time-stretch by the pitch factor,
// then resample by it. This is a line-for-line port of PitchShifter.java in
// android-engine; both ends must keep the same algorithm and parameters so the
// same text produces subjectively identical audio.
const (
grain = 1024
overlap = 512
hops = grain - overlap
search = 128
)
func PitchShiftNeeded(pitch float32) bool {
return math.Abs(float64(pitch-1)) >= 0.01
}
func ShiftPitch(samples []float32, factor float32) []float32 {
if len(samples) == 0 || !PitchShiftNeeded(factor) {
return samples
}
stretched := timeStretch(samples, factor)
return resample(stretched, factor)
}
func timeStretch(in []float32, factor float32) []float32 {
hopA := roundInt(float32(hops) / factor)
if hopA < 1 {
hopA = 1
}
window := hann(grain)
expected := roundInt(float32(len(in)) * factor)
if expected < grain {
expected = grain
}
out := make([]float32, expected+grain)
inPos, outPos := 0, 0
for inPos+grain <= len(in) {
best := inPos
if outPos > 0 {
from := inPos - search
if from < 0 {
from = 0
}
to := inPos + search
if to > len(in)-grain {
to = len(in) - grain
}
bestCorr := -1.0
for cand := from; cand <= to; cand += 4 {
var corr float64
for i := 0; i < overlap; i++ {
corr += float64(in[cand+i]) * float64(out[outPos+i])
}
if corr > bestCorr {
bestCorr = corr
best = cand
}
}
}
for i := 0; i < grain; i++ {
out[outPos+i] += in[best+i] * window[i]
}
inPos += hopA
outPos += hops
}
result := make([]float32, expected)
copy(result, out[:min(expected, len(out))])
return result
}
func resample(in []float32, factor float32) []float32 {
outLen := roundInt(float32(len(in)) / factor)
if outLen < 1 {
outLen = 1
}
out := make([]float32, outLen)
for i := 0; i < outLen; i++ {
pos := float64(i) * float64(factor)
i0 := int(pos)
if i0 >= len(in) {
break
}
i1 := i0 + 1
if i1 > len(in)-1 {
i1 = len(in) - 1
}
frac := pos - float64(i0)
out[i] = float32(float64(in[i0])*(1-frac) + float64(in[i1])*frac)
}
return out
}
func hann(size int) []float32 {
w := make([]float32, size)
for i := 0; i < size; i++ {
w[i] = float32(0.5 - 0.5*math.Cos(2*math.Pi*float64(i)/float64(size-1)))
}
return w
}
// roundInt matches Java Math.round(float): floor(x + 0.5).
func roundInt(x float32) int {
return int(math.Floor(float64(x) + 0.5))
}
+56
View File
@@ -0,0 +1,56 @@
package tts
import (
"math"
"testing"
)
func TestShiftPitchIdentity(t *testing.T) {
in := []float32{0.1, -0.2, 0.3}
out := ShiftPitch(in, 1.0)
if &out[0] != &in[0] {
t.Fatal("factor 1.0 should return the input slice unchanged")
}
}
func TestShiftPitchKeepsDuration(t *testing.T) {
const rate = 22050
in := make([]float32, rate)
for i := range in {
in[i] = float32(0.5 * math.Sin(2*math.Pi*220*float64(i)/rate))
}
for _, factor := range []float32{0.5, 1.2, 2.0} {
out := ShiftPitch(in, factor)
if len(out) == 0 {
t.Fatalf("factor %v: empty output", factor)
}
if diff := math.Abs(float64(len(out))/float64(len(in)) - 1); diff > 0.05 {
t.Fatalf("factor %v: duration changed by %.1f%% (%d vs %d samples)",
factor, diff*100, len(out), len(in))
}
var peak float32
for _, v := range out {
if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) {
t.Fatalf("factor %v: non-finite sample", factor)
}
if v < 0 {
v = -v
}
if v > peak {
peak = v
}
}
if peak < 0.2 {
t.Fatalf("factor %v: signal collapsed (peak %.3f)", factor, peak)
}
}
}
func TestShiftPitchSilence(t *testing.T) {
out := ShiftPitch(make([]float32, 5000), 1.5)
for i, v := range out {
if v != 0 {
t.Fatalf("sample %d: got %v, want 0", i, v)
}
}
}
+181
View File
@@ -0,0 +1,181 @@
package tts
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// Manifest mirrors android-engine voices.example/manifest.json so a single
// file configures both the Android engine and this server.
type Manifest struct {
Version string `json:"version"`
Default string `json:"default"`
Voices []VoiceEntry `json:"voices"`
}
type VoiceEntry struct {
Name string `json:"name"`
Locale string `json:"locale"`
Label string `json:"label"`
SpeakerID int `json:"speakerId"`
Quality int `json:"quality"`
Dir string `json:"dir"`
Model string `json:"model"`
Lexicon string `json:"lexicon"`
Tokens string `json:"tokens"`
DataDir string `json:"dataDir"`
RuleFsts []string `json:"ruleFsts"`
}
type VoicePack struct {
Name string
Locale string
Label string
SpeakerID int
Quality int
ModelPath string
LexiconPath string
TokensPath string
DataDir string
RuleFsts string
}
type Repo struct {
Version string
Default string
Packs []*VoicePack
byName map[string]*VoicePack
}
func LoadRepo(root string) (*Repo, error) {
raw, err := os.ReadFile(filepath.Join(root, "manifest.json"))
if err != nil {
return nil, fmt.Errorf("read manifest: %w", err)
}
var m Manifest
if err := json.Unmarshal(raw, &m); err != nil {
return nil, fmt.Errorf("parse manifest: %w", err)
}
if len(m.Voices) == 0 {
return nil, fmt.Errorf("manifest has no voices")
}
repo := &Repo{Version: m.Version, Default: m.Default, byName: make(map[string]*VoicePack, len(m.Voices))}
for _, e := range m.Voices {
if e.Name == "" {
return nil, fmt.Errorf("voice entry without name")
}
if _, dup := repo.byName[e.Name]; dup {
return nil, fmt.Errorf("duplicate voice %q", e.Name)
}
base := root
if e.Dir != "" {
base = filepath.Join(root, e.Dir)
}
tokens := e.Tokens
if tokens == "" {
tokens = "tokens.txt"
}
rules := make([]string, 0, len(e.RuleFsts))
for _, f := range e.RuleFsts {
rules = append(rules, filepath.Join(base, f))
}
pack := &VoicePack{
Name: e.Name,
Locale: e.Locale,
Label: e.Label,
SpeakerID: e.SpeakerID,
Quality: e.Quality,
ModelPath: filepath.Join(base, e.Model),
TokensPath: filepath.Join(base, tokens),
RuleFsts: strings.Join(rules, ","),
}
if e.Lexicon != "" {
pack.LexiconPath = filepath.Join(base, e.Lexicon)
}
if e.DataDir != "" {
pack.DataDir = filepath.Join(base, e.DataDir)
}
if pack.Label == "" {
pack.Label = pack.Name
}
if err := pack.validate(); err != nil {
return nil, err
}
repo.Packs = append(repo.Packs, pack)
repo.byName[pack.Name] = pack
}
if _, ok := repo.byName[repo.Default]; !ok {
repo.Default = repo.Packs[0].Name
}
return repo, nil
}
func (p *VoicePack) validate() error {
required := []string{p.ModelPath, p.TokensPath}
if p.LexiconPath != "" {
required = append(required, p.LexiconPath)
}
if p.DataDir != "" {
required = append(required, p.DataDir)
}
if p.RuleFsts != "" {
required = append(required, strings.Split(p.RuleFsts, ",")...)
}
for _, path := range required {
if _, err := os.Stat(path); err != nil {
return fmt.Errorf("voice %q: %w", p.Name, err)
}
}
return nil
}
func (r *Repo) DefaultPack() *VoicePack {
return r.byName[r.Default]
}
// Resolve accepts a voice name or a BCP-47 language tag and falls back to the
// default pack, matching VoiceRepository.resolve on the Android side.
func (r *Repo) Resolve(requested string) *VoicePack {
requested = strings.TrimSpace(requested)
if requested == "" {
return r.DefaultPack()
}
if p, ok := r.byName[requested]; ok {
return p
}
want := normalizeLanguage(requested)
if want != "" {
for _, p := range r.Packs {
if languageOf(p.Locale) == want {
return p
}
}
}
return r.DefaultPack()
}
func languageOf(locale string) string {
tag := strings.ToLower(strings.ReplaceAll(locale, "_", "-"))
if i := strings.IndexByte(tag, '-'); i >= 0 {
tag = tag[:i]
}
return normalizeLanguage(tag)
}
func normalizeLanguage(tag string) string {
tag = strings.ToLower(strings.ReplaceAll(strings.TrimSpace(tag), "_", "-"))
if i := strings.IndexByte(tag, '-'); i >= 0 {
tag = tag[:i]
}
switch tag {
case "cmn", "zho", "zh":
return "zh"
default:
return tag
}
}
+117
View File
@@ -0,0 +1,117 @@
package tts
import (
"os"
"path/filepath"
"testing"
)
func writeVoiceFiles(t *testing.T, root, dir string) {
t.Helper()
files := map[string]string{
"model.onnx": "model",
"tokens.txt": "tokens",
"lexicon.txt": "lexicon",
"phone.fst": "fst",
}
for name, content := range files {
path := filepath.Join(root, dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
}
func writeManifest(t *testing.T, root, content string) {
t.Helper()
if err := os.WriteFile(filepath.Join(root, "manifest.json"), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
const testManifest = `{
"version": "test-1",
"default": "a",
"voices": [
{"name": "a", "locale": "zh-CN", "label": "甲", "speakerId": 0, "quality": 300,
"dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]},
{"name": "b", "locale": "yue-HK", "label": "乙", "speakerId": 1, "quality": 300,
"dir": "pack-b", "model": "model.onnx", "lexicon": "lexicon.txt", "ruleFsts": ["phone.fst"]}
]
}`
func TestLoadRepoAndResolve(t *testing.T) {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
writeVoiceFiles(t, root, "pack-b")
writeManifest(t, root, testManifest)
repo, err := LoadRepo(root)
if err != nil {
t.Fatal(err)
}
if repo.Version != "test-1" || repo.Default != "a" || len(repo.Packs) != 2 {
t.Fatalf("unexpected repo: %+v", repo)
}
cases := map[string]string{
"": "a",
"a": "a",
"b": "b",
"zh-CN": "a",
"cmn": "a",
"yue-HK": "b",
"yue": "b",
"nope": "a",
}
for requested, want := range cases {
if got := repo.Resolve(requested).Name; got != want {
t.Fatalf("Resolve(%q) = %q, want %q", requested, got, want)
}
}
if repo.Packs[0].RuleFsts != filepath.Join(root, "pack-a", "phone.fst") {
t.Fatalf("rule fst path %q", repo.Packs[0].RuleFsts)
}
}
func TestLoadRepoMissingModel(t *testing.T) {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
writeManifest(t, root, testManifest)
if _, err := LoadRepo(root); err == nil {
t.Fatal("expected error for missing pack-b files")
}
}
func TestLoadRepoDuplicateName(t *testing.T) {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
writeManifest(t, root, `{
"version": "t", "default": "a",
"voices": [
{"name": "a", "locale": "zh-CN", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"},
{"name": "a", "locale": "yue-HK", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"}
]
}`)
if _, err := LoadRepo(root); err == nil {
t.Fatal("expected duplicate name error")
}
}
func TestLoadRepoDefaultFallsBackToFirst(t *testing.T) {
root := t.TempDir()
writeVoiceFiles(t, root, "pack-a")
writeManifest(t, root, `{
"version": "t", "default": "missing",
"voices": [{"name": "a", "locale": "zh-CN", "dir": "pack-a", "model": "model.onnx", "lexicon": "lexicon.txt"}]
}`)
repo, err := LoadRepo(root)
if err != nil {
t.Fatal(err)
}
if repo.Default != "a" {
t.Fatalf("default %q, want a", repo.Default)
}
}
+47
View File
@@ -0,0 +1,47 @@
package tts
import (
"encoding/binary"
"math"
)
const wavHeaderSize = 44
// EncodeWAV writes signed 16-bit little-endian mono PCM. Sample conversion
// matches PcmWriter.java: clamp to [-1, 1], scale by 32767, round half up.
func EncodeWAV(samples []float32, sampleRate int) []byte {
dataSize := len(samples) * 2
buf := make([]byte, wavHeaderSize+dataSize)
copy(buf[0:], "RIFF")
binary.LittleEndian.PutUint32(buf[4:], uint32(36+dataSize))
copy(buf[8:], "WAVE")
copy(buf[12:], "fmt ")
binary.LittleEndian.PutUint32(buf[16:], 16)
binary.LittleEndian.PutUint16(buf[20:], 1)
binary.LittleEndian.PutUint16(buf[22:], 1)
binary.LittleEndian.PutUint32(buf[24:], uint32(sampleRate))
binary.LittleEndian.PutUint32(buf[28:], uint32(sampleRate*2))
binary.LittleEndian.PutUint16(buf[32:], 2)
binary.LittleEndian.PutUint16(buf[34:], 16)
copy(buf[36:], "data")
binary.LittleEndian.PutUint32(buf[40:], uint32(dataSize))
for i, v := range samples {
if v > 1 {
v = 1
} else if v < -1 {
v = -1
}
s := int32(math.Floor(float64(v*32767) + 0.5))
binary.LittleEndian.PutUint16(buf[wavHeaderSize+i*2:], uint16(s))
}
return buf
}
func WAVSampleRate(wav []byte) int {
if len(wav) < wavHeaderSize {
return 0
}
return int(binary.LittleEndian.Uint32(wav[24:28]))
}
+36
View File
@@ -0,0 +1,36 @@
package tts
import (
"encoding/binary"
"testing"
)
func TestEncodeWAV(t *testing.T) {
wav := EncodeWAV([]float32{0, 1, -1, 2, -2, 0.5}, 22050)
if len(wav) != wavHeaderSize+12 {
t.Fatalf("length %d, want %d", len(wav), wavHeaderSize+12)
}
if string(wav[0:4]) != "RIFF" || string(wav[8:12]) != "WAVE" ||
string(wav[12:16]) != "fmt " || string(wav[36:40]) != "data" {
t.Fatalf("bad chunk tags: %q %q %q %q", wav[0:4], wav[8:12], wav[12:16], wav[36:40])
}
if rate := WAVSampleRate(wav); rate != 22050 {
t.Fatalf("sample rate %d, want 22050", rate)
}
if bits := binary.LittleEndian.Uint16(wav[34:36]); bits != 16 {
t.Fatalf("bits per sample %d, want 16", bits)
}
want := []int16{0, 32767, -32767, 32767, -32767, 16384}
for i, w := range want {
got := int16(binary.LittleEndian.Uint16(wav[wavHeaderSize+i*2:]))
if got != w {
t.Fatalf("sample %d: got %d, want %d", i, got, w)
}
}
}
func TestWAVSampleRateShortInput(t *testing.T) {
if got := WAVSampleRate([]byte{1, 2, 3}); got != 0 {
t.Fatalf("got %d, want 0", got)
}
}