- android-engine:TextToSpeechService 引擎,含设置页、语音包导入(SHA-256 校验)与预热 - server:Go CPU 合成服务与部署文件 - test-client:端到端验证客户端 - 模型与语音包不入库,见 models/README.md
55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
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"))
|
|
} |