feat(tts): change the speech speed without a restart and keep fast speech clear

MeloTTS's own speed shortens every sound and slurred fast speech (Whisper
large-v3 on five Korean sentences, three renders each: 5.5% character
errors at 1.5 and 20% at 2.0, against 1.4% at 1.0). The MeloTTS child now
speaks at most at its natural pace and makes faster speech with a WSOLA
time stretch that keeps the pitch (1.9% at 1.5, 2.2% at 2.0, about 15 ms
per 4 s of speech).

A voice.tts.speed saved while the services run goes to the worker at once
(new tts_speed message) and applies from the next sentence; the client
sends it again whenever the worker connects again. Version 0.1.4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-15 23:39:04 +09:00
parent d17a3bbb61
commit dbe5c617bc
17 changed files with 268 additions and 16 deletions

View File

@@ -2,11 +2,18 @@
Stand-alone on purpose: it must not import the worker package, which lives in another venv.
stdin: one JSON request per line: {"text": "...", "rate": 48000}
stdin: one JSON request per line: {"text": "...", "rate": 48000, "speed": 1.5} (speed optional,
default --speed)
stdout: frames of u32 LE header length | header JSON | payload. The first frame is
{"ready": true, "rate": <native rate>}; each reply is {"ok": true, "samples": N} followed by N
int16 LE mono samples at the requested rate, or {"ok": false, "error": "..."} with no payload.
Library output that would land on stdout is sent to stderr so it cannot corrupt the frames.
Speed: MeloTTS's own speed shortens every sound and slurs faster speech (Whisper large-v3 on five
Korean sentences, three renders each: character errors 5.5% at 1.5 and 20% at 2.0, against 1.4% at
1.0). So the model speaks at most at MODEL_SPEED_MAX (its natural pace) and a time stretch that keeps
the pitch (WSOLA) makes it faster: 1.9% at 1.5 and 2.2% at 2.0. Letting the model go to 1.25 first
measured slightly worse (2.2% and 3.1%).
"""
from __future__ import annotations
@@ -19,6 +26,42 @@ import struct
import sys
import types
MODEL_SPEED_MAX = 1.0
def split_speed(speed: float) -> tuple[float, float]:
"""(the model's speed, the stretch factor after it); their product is ``speed``."""
model = min(speed, MODEL_SPEED_MAX)
return model, speed / model
def stretch(audio, factor: float, rate: int, frame_ms: float = 30.0, search_ms: float = 10.0):
"""Shorten ``audio`` by ``factor`` and keep its pitch (WSOLA): half-overlapping Hann frames are
taken ``factor`` times further apart than they are laid down, each shifted within ``search_ms``
to where it best continues the frame before it, so the pieces join without dips or clicks."""
import numpy as np
x = np.asarray(audio, dtype=np.float64)
if abs(factor - 1.0) < 1e-3 or len(x) == 0:
return x
n = int(rate * frame_ms / 1000) // 2 * 2
hop = n // 2
tol = int(rate * search_ms / 1000)
win = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(n) / n) # its half-overlapped copies sum to 1
n_out = int(np.ceil(len(x) / factor))
frames = n_out // hop + 2
xp = np.pad(x, (tol, int(frames * hop * factor) + 2 * n + 2 * tol))
y = np.zeros(frames * hop + n)
prev = None
for k in range(frames):
pos = int(round(k * hop * factor)) + tol
if prev is not None:
natural = xp[prev + hop: prev + hop + n]
pos += int(np.argmax(np.correlate(xp[pos - tol: pos + tol + n], natural, mode="valid"))) - tol
y[k * hop: k * hop + n] += xp[pos: pos + n] * win
prev = pos
return y[:n_out]
def korean_only_patches() -> None:
"""MeloTTS imports its Japanese front end (module-level MeCab.Tagger()) even for Korean, and on
@@ -76,7 +119,7 @@ def main() -> int:
spk_map = model.hps.data.spk2id
speaker = spk_map[args.language] if args.language in spk_map else spk_map[list(spk_map.keys())[0]]
native = int(model.hps.data.sampling_rate)
model.tts_to_file("워밍업입니다.", speaker, None, speed=args.speed, quiet=True)
model.tts_to_file("워밍업입니다.", speaker, None, speed=split_speed(args.speed)[0], quiet=True)
except Exception as e:
reply({"ready": False, "error": f"{type(e).__name__}: {e}"})
return 1
@@ -86,8 +129,9 @@ def main() -> int:
try:
req = json.loads(line)
rate = int(req["rate"])
audio = model.tts_to_file(str(req["text"]), speaker, None, speed=args.speed, quiet=True)
audio = np.asarray(audio, dtype=np.float64)
model_speed, factor = split_speed(float(req.get("speed", args.speed)))
audio = model.tts_to_file(str(req["text"]), speaker, None, speed=model_speed, quiet=True)
audio = stretch(audio, factor, native)
if rate != native:
from math import gcd
g = gcd(rate, native)