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