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)

View File

@@ -346,6 +346,7 @@ class Session:
kind = msg.get("type")
handler = {"speaking_end": self._on_speaking_end, "speaker_leave": self._on_speaker_leave,
"config": self._on_config, "tts": self._on_tts, "tts_cancel": self._on_tts_cancel,
"tts_speed": self._on_tts_speed,
"voice_join": self._on_voice_join, "voice_leave": lambda m: self._leave_voice(),
"member_join": self._on_member_join, "member_leave": self._on_member_leave,
"chat_message": self._on_chat_message, "chat_edit": self._on_chat_edit,
@@ -388,6 +389,15 @@ class Session:
self.worker.scheduler.drop_partials(lambda key: key[0] == self.sid)
debug_log(f"session {self.sid} settings changed: {sorted(changes)}", "voice_worker")
def _on_tts_speed(self, msg: dict) -> None:
speed = msg.get("speed")
if isinstance(speed, bool) or not isinstance(speed, (int, float)) or not 0.5 <= speed <= 2.0:
self.error("bad_message", "tts_speed needs a speed from 0.5 to 2.0")
return
if self.worker.tts_engine is not None:
self.worker.tts_engine.speed = float(speed)
debug_log(f"tts speed {speed}", "tts")
def _on_tts(self, msg: dict) -> None:
rid, text, more = msg.get("id"), msg.get("text", ""), msg.get("more", False)
if not isinstance(rid, str) or not 0 < len(rid.encode()) < 256 or not isinstance(text, str) \

View File

@@ -19,6 +19,8 @@ CHILD = os.path.join(os.path.dirname(os.path.abspath(__file__)), "melo_child.py"
class MeloEngine:
def __init__(self, python: str, device: str = "cuda", speed: float = 1.5, language: str = "KR"):
self.cmd = [python, CHILD, "--device", device, "--speed", str(speed), "--language", language]
# Read for each sentence, so a new speed (`tts_speed`) applies from the next one.
self.speed = speed
self._lock = threading.Lock()
self._proc: subprocess.Popen | None = None
self.native_rate: int | None = None
@@ -49,7 +51,7 @@ class MeloEngine:
if self._proc is None or self._proc.poll() is not None:
debug_log("melo child not running, restarting", "tts")
self._start()
self._proc.stdin.write((json.dumps({"text": text, "rate": rate}) + "\n").encode())
self._proc.stdin.write((json.dumps({"text": text, "rate": rate, "speed": self.speed}) + "\n").encode())
self._proc.stdin.flush()
header, payload = self._read()
if not header.get("ok"):

View File

@@ -164,6 +164,7 @@ line (-0.6) would lose more real words than it saves.
```
-> {"type": "tts", "id": "r1", "text": "...", "more": false} // more=true: more text follows for r1
-> {"type": "tts_cancel", "id": "r1"}
-> {"type": "tts_speed", "speed": 1.8} // 0.5-2.0, from the next sentence on
<- binary 0x02 | u8 n | id (n bytes UTF-8) | u32 LE seq | PCM16LE in the hello "tts" format
<- {"type": "tts_done", "id": "r1", "chunks": 3, "cancelled": false, "failed": false}
```
@@ -178,6 +179,14 @@ is ready. Requests are served first come, first served by one TTS engine. `tts_c
request's unsent sentences, and `tts_done` follows with `cancelled: true`. A sentence that fails to
synthesise is reported with `error` (`code: "tts_failed"`) and the request ends with `failed: true`.
Speed starts at `--melo-speed` and `tts_speed` changes it for every sentence made after it (a speed
outside 0.5-2.0 or not a number is `bad_message` and the last good one stays). MeloTTS itself speaks
at most at its natural pace (1.0): its own speed shortens every sound and slurs faster 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). Faster speech is made at 1.0 and shortened with WSOLA, a time stretch
that keeps the pitch (30 ms half-overlapping Hann frames, each shifted within 10 ms to where it best
continues the one before): 1.9% at 1.5 and 2.2% at 2.0, about 15 ms per 4 s of speech.
### History and brain (M3)
The worker also hosts the brain (the existing `jarvis` reply engine) and the conversation history