Text-to-Speech
Decision
The robot uses a provider-independent TTSProvider interface.
The application must not depend directly on Piper, an OpenAI TTS SDK, Home Assistant TTS or another vendor implementation outside the corresponding provider adapter.
Implemented local provider: Piper
Piper is the preferred first local TTS engine because the project targets a Raspberry Pi 3 and should retain useful offline speech capability.
PiperTTSProvider lazily loads the installed piper-tts Python voice API once
in the main PHOS runtime process, then reuses that in-memory model for each secure
temporary WAV. An AudioOutputProvider plays that artifact and the runtime removes
it afterwards. Piper never selects a speaker device directly.
Models are local deployment assets, normally under models/tts/piper/, and are
not committed. Configure tts.local.model_path (plus an optional Piper
speaker_id) and install the piper-tts package on the Pi. The canonical tts section is
disabled by default, uses provider: local, engine: piper, and aplay output.
When enabled, a failed model/Python API is reported when speech is requested;
disabled TTS does not affect startup.
On the reference Raspberry Pi HDMI deployment, PHOS normalizes Piper output at
the playback boundary to 48000 Hz, stereo, PCM16 (sample_rate: 48000,
channels: 2, sample_width: 2). Piper synthesis itself is unchanged. A
1000 ms low-amplitude non-zero 440 Hz warm-up signal is then prepended in that
same target format and the resulting temporary WAV is passed to aplay once.
Set preroll_ms: 0 to disable only the warm-up; other outputs may configure a
different target format. This is an HDMI output workaround, not a Piper
synthesis change.
For diagnostics, each accepted utterance receives a monotonically increasing request
identifier; its logs use PHOS SPEECH[n] for acceptance, synthesis, WAV validation,
normalization, playback, and terminal task cleanup. PHOS logs monotonic durations for synthesis, normalization,
aplay playback and total completion, along with final WAV technical metadata
(rate, channels, PCM sample width, frames and duration). Source Piper WAVs must
also be non-empty, uncompressed, and non-silent before they can reach playback.
It never logs speech
text or audio content. REST-triggered speech uses this exact same runtime-owned
Piper → normalized/prerolled single WAV → one aplay path. The first utterance
includes lazy model loading and logs piper_model_load_*; later utterances reuse
the loaded voice. Optional localized interaction query responses use this same
application-owned path when interaction.response_tts_enabled is true; they do
not select a provider or add a language argument to the current text-only
TTSProvider contract. PHOS does not run a persistent Piper server.
Diagnosing intermittent HDMI playback
tts.audio_output.debug.retain_final_wav is disabled by default. Set it to
true only while diagnosing playback. For a REST request, PHOS makes a
byte-identical diagnostic copy at
/tmp/phos-speech-<pid>-<request-id>-<unique>.wav before playback. This is the
exact final WAV supplied to the selected output provider: the normalized/prerolled
WAV for ALSA, or the generated WAV for PipeWire. The normal temporary artifact is
removed after playback; retained diagnostics are not removed automatically, do
not overwrite prior samples, and can accumulate under /tmp. Retention is
best-effort: collisions, permission failures, and filesystem errors are logged as
warnings but never prevent speech playback. Successful retention logs the path
and byte count as PHOS SPEECH: retained_wav.
Every request logs sanitized final-WAV metadata (format, frames, duration, peak,
RMS, byte size, and SHA-256 prefix), plus the selected aplay executable/device,
return code, and duration. DEBUG logging also emits the selected ALSA target.
PHOS invokes the deterministic command aplay -q [-D <configured-device>]
<final-wav> using a file path, never stdin. When device is configured, that
same device is supplied on every attempt; otherwise ALSA's default-device
resolution is necessarily used and is logged as default.
tts.audio_output.retry.max_attempts defaults to 2 (and is capped at two),
with a 200 ms retry.delay_ms. A nonzero aplay result, timeout, or execution
error retries playback of the exact same finalized WAV once. Piper synthesis is
never retried. A zero exit status means only that aplay consumed the WAV; it
does not prove that HDMI rendered intelligible audio, so PHOS does not retry a
successful process merely because physical output cannot be observed in software.
The selected user, runtime directory, ALSA/Pulse/PipeWire variables, working
directory, and process group are emitted only at DEBUG level to compare service
and manual-shell execution safely.
PipeWire output
Set tts.audio_output.player: pipewire to select PipeWire (pw-play) in Voice
& Speech. PHOS then passes the generated WAV directly to pw-play and waits for
completion; it does not apply the ALSA HDMI normalization or warm-up signal.
pw-play must be available when the live candidate is activated, otherwise the
saved and active audio output remain unchanged. PipeWire chooses its default
sink, so Bluetooth pairing, reconnection, volume, and sink selection remain OS
responsibilities. Leave tts.audio_output.device as null for PipeWire.
PipeWire playback emits bounded PHOS AUDIO start, completion-duration, and
failure-reason logs. The default remains aplay, preserving existing ALSA
installations.
After a noisy request, replay its retained artifact without regenerating speech:
aplay /tmp/phos-speech-<pid>-<request-id>-<unique>.wav
Use aplay -D <configured-device> when tts.audio_output.device is configured.
If that replay is clean, the artifact was valid and the remaining issue is HDMI or
ALSA sink state. If it is noisy too, compare its metadata/checksum to a good
request: the problem is in final-artifact generation. A zero aplay exit status
alone is not evidence that HDMI rendered intelligible audio.
HDMI audio can also be affected when the display enters standby. The reference deployment keeps its X11 face display active while PHOS runs; see face display session guidance.
Architecture
Robot / behavior
|
v
TTSProvider
|
+--> PiperTTSProvider local/offline
+--> ElevenLabsTTSProvider
+--> CartesiaTTSProvider
+--> future Google Cloud TTS provider
TTSProviderFactory selects the configured provider only in the main PHOS
runtime process. The Web Admin edits canonical configuration and never creates
a provider. local (Piper), elevenlabs, and cartesia are implemented
selections; google remains reserved and unavailable. The factory never falls
back to Piper. ElevenLabs uses the official SDK's non-streaming convert call
with a configured lossless PCM output, wraps the result as a WAV, and uses the
same normalization/preroll/playback path as Piper. Configure a Voice ID in Voice
& speech; the ElevenLabs API key stays write-only in Web Admin's Credentials
page and never YAML. Model ID and PCM output format remain configurable. Provider
changes use live candidate activation: successful changes persist, failed
activation keeps the prior provider/configuration, and an in-progress speech
operation retains its original provider/output reference. Runtime status shows
configured and active provider separately, with Unknown where a runtime snapshot
is unavailable. Streaming is not implemented. ElevenLabs integration is
implemented, but account and voice-plan restrictions can prevent end-to-end
physical availability.
Cartesia uses the official synchronous SDK with a configured sonic-3.6 model,
explicit Voice ID, and the pinned Cartesia API revision 2026-08-14. It requests
a WAV containing 44.1 kHz mono PCM16, then hands that artifact unchanged to the
same PHOS normalization, preroll, and one-aplay playback path used by every
provider. Its API key is write-only in Credentials; Voice ID, model ID, and
sample rate, speed, and volume are canonical Voice & Speech settings.
Known ElevenLabs API failures are classified without logging SDK responses: authentication failures, plan-required responses, missing voices, rate limits, and provider/network unavailability become stable PHOS TTS error codes. These are expected warnings rather than tracebacks; the speech state still returns to idle and the API reports TTS as unavailable until a later request succeeds.
TTS is optional. If an enabled configured provider cannot initialize—for example
the ElevenLabs SDK is not installed, its credential is absent, or a local model
is unavailable—PHOS logs a sanitized PHOS TTS warning and continues startup.
Runtime status distinguishes disabled from an enabled-but-unavailable provider
and reports only a safe reason such as missing_dependency or
missing_credential. Speech requests then return the normal tts_unavailable
response; PHOS never silently substitutes Piper.
After deployment, install the updated optional dependencies with the documented
environment command: .venv/bin/pip install -e '.[all]'.
Cartesia diagnostic request
For direct Cartesia request diagnostics without starting PHOS, export the API key only into the current shell and run:
export CARTESIA_API_KEY='...'
.venv/bin/python scripts/test_cartesia_tts.py --voice-id <VOICE_ID>
The diagnostic script uses the official SDK with Cartesia API revision
2026-08-14, writes a WAV without playing it, and prints only safe response and
WAV metadata. Model, version, text, and destination can be overridden:
.venv/bin/python scripts/test_cartesia_tts.py --voice-id <VOICE_ID> \
--model-id sonic-3.6 --api-version 2026-08-14 --text "Hello from PHOS" \
--output /tmp/cartesia-test.wav
For truncation checks, use a multi-sentence --text value. The script prints
the complete output path, total bytes, and WAV duration, but never plays audio.
Contract
TTSProvider.synthesize() receives a neutral TTSRequest and returns a neutral TTSResult.
Provider-specific SDK objects must never escape the adapter.
Responsibilities
TTSProvider
- define the stable synthesis contract
- carry text, language and optional voice
- return the generated audio path and neutral metadata
PiperTTSProvider
- translate the neutral request into a Piper Python API synthesis call
- write audio to the requested output path
- convert Piper failures into explicit application errors
Audio playback
Playback is a separate responsibility. TTSProvider generates audio; it does not own speaker selection, volume, ALSA/PipeWire configuration or playback lifecycle. AudioOutputProviderFactory selects either ALSA (aplay) or PipeWire (pw-play) independently of the TTS provider.
Raspberry Pi 3 constraints
- Prefer local TTS for low-latency/offline system phrases when practical.
- Benchmark voice/model quality versus synthesis latency on the Pi 3.
- Do not assume every Piper model performs acceptably on the Pi 3.
- Keep model path and executable path configurable.
- Do not bundle large voice models in the source repository.
Future providers
A new provider must implement TTSProvider without changing callers.
Local/Piper, Cartesia, and ElevenLabs are implemented selections; Google remains
reserved and unavailable. Future examples may include Home Assistant TTS or a
LAN-hosted synthesis service.
Raspberry Pi validation
- Install the
piper-ttsPython package and place a small voice model and metadata beside each other undermodels/tts/piper/. - Set
tts.enabled: trueandtts.local.model_pathin the active config. - Start PHOS and invoke the application
speak()path with a short phrase. - Confirm audible ALSA output,
IDLE → SPEAKING → IDLE, and temporary WAV cleanup. - Exercise microphone/Vosk listening afterwards to confirm no STT regression.