tts

package
v0.81.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 36 Imported by: 3 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tts exposes the embeddable SpeechKit text-to-speech surface.

Stability: Stable — no breaking change without a minor version bump and a changelog callout.

Index

Constants

View Source
const (
	FluxSpeechStarted   = "SpeechStarted"
	FluxSpeechFlushed   = "Flushed"
	FluxSpeechMetadata  = "SpeechMetadata"
	FluxSpeechInterrupt = "Interrupt"
)

Flux TTS server event types. A turn opens with SpeechStarted, Flushed acknowledges the client's Flush, and SpeechMetadata closes the turn with its duration and billing counts. Interrupt arrives instead when the listener barges in.

View Source
const (
	// GeminiTTSModelFlash is the flagship Gemini 3.8 speech model.
	GeminiTTSModelFlash = "gemini-3.8-flash-tts"
	// GeminiTTSModelFlashLite is the high-throughput Gemini 3.8 speech model.
	GeminiTTSModelFlashLite = "gemini-3.8-flash-lite-tts"
	// GeminiTTSDefaultModel is used when [GeminiOpts.Model] is empty.
	GeminiTTSDefaultModel = GeminiTTSModelFlashLite
	// GeminiTTSDefaultVoice is the prebuilt voice used when none is configured.
	GeminiTTSDefaultVoice = "Kore"
)

Gemini 3.8 TTS model ids served by the Gemini API Interactions endpoint.

View Source
const (

	// DeepgramFluxTTSDefaultVoice is Deepgram's default Flux TTS voice.
	DeepgramFluxTTSDefaultVoice = "flux-kit-en"
)
View Source
const ProfileSherpaPiper = "tts.local.sherpa-piper"

ProfileSherpaPiper is the catalog profile that pins ProviderSherpaPiper.

View Source
const ProviderSherpaPiper = "sherpa_piper"

ProviderSherpaPiper is the provider name of the bundled on-device Piper voices that run through the speechkit-tts-sherpa sidecar.

Variables

View Source
var ErrMissingRouter = errors.New("speechkit tts: router is required")

ErrMissingRouter is returned by NewService and Service.Synthesize when no Router is configured.

Functions

func IsDeepgramFluxVoice added in v0.54.10

func IsDeepgramFluxVoice(voice string) bool

IsDeepgramFluxVoice reports whether a voice id names a Flux TTS voice rather than an Aura one.

func IsMAIVoice added in v0.68.24

func IsMAIVoice(shortName string) bool

IsMAIVoice reports whether shortName addresses a Microsoft MAI voice ("de-DE-Mia:MAI-Voice-2") rather than a classic neural voice.

func MAIVoiceFamilies added in v0.68.24

func MAIVoiceFamilies() []string

MAIVoiceFamilies lists the MAI model series a voice short name can end in.

func PreferredProviderForProfileID

func PreferredProviderForProfileID(profileID string) string

PreferredProviderForProfileID maps a Voice-Output profile ID to Provider.Name. The mapping is shared with the kernel via the ttsroute leaf package.

func SnapDeepgramFluxSpeed added in v0.54.10

func SnapDeepgramFluxSpeed(speed float64) float64

SnapDeepgramFluxSpeed rounds a speed onto the discrete steps Flux TTS accepts, clamping to the nearest bound. It returns 0 for "unset" so callers can omit the parameter.

func VoiceLocale added in v0.68.24

func VoiceLocale(shortName string) string

VoiceLocale returns the BCP-47 locale a Speech voice short name starts with: "de-DE" for "de-DE-Mia:MAI-Voice-2". Empty when the name carries no language-region prefix.

Types

type AzureSpeech added in v0.68.24

type AzureSpeech struct {
	Host       string
	Validation netsec.ValidationOptions
	// contains filtered or unexported fields
}

AzureSpeech implements Provider on the Azure Speech SSML endpoint of a Microsoft Foundry resource. Microsoft's MAI-Voice models are served there, not on the OpenAI-compatible audio/speech route Foundry uses for gpt-*-tts, so this adapter talks to the resource's custom domain directly.

It reports the same provider id as Foundry ("foundry"): routing, preference pinning and option manifests key on the provider, not on the wire format. Validation is strict by default (public https only).

func NewAzureSpeech added in v0.68.24

func NewAzureSpeech(opts AzureSpeechOpts) *AzureSpeech

NewAzureSpeech creates an Azure Speech TTS provider for MAI voices.

func (*AzureSpeech) Capabilities added in v0.68.24

func (*AzureSpeech) Capabilities() []speechkit.Capability

Capabilities implements CapabilityReporter; AzureSpeech reports speechkit.CapabilityTTS only.

func (*AzureSpeech) CloseIdleConnections added in v0.68.24

func (a *AzureSpeech) CloseIdleConnections()

CloseIdleConnections drops idle keep-alive connections in the provider's HTTP client. It is safe on a nil receiver.

func (*AzureSpeech) Health added in v0.68.24

func (a *AzureSpeech) Health(ctx context.Context) error

Health lists the voices: free, read-only, and it exercises the same host and credential Synthesize uses.

func (*AzureSpeech) Kind added in v0.68.24

func (a *AzureSpeech) Kind() ProviderKind

Kind reports ProviderKindDirectProvider: the resource's own API.

func (*AzureSpeech) ListVoices added in v0.68.24

func (a *AzureSpeech) ListVoices(ctx context.Context) ([]AzureSpeechVoice, error)

ListVoices fetches the voices the resource can synthesize with, MAI and classic neural alike; callers filter on IsMAIVoice or ModelSeries.

func (*AzureSpeech) Name added in v0.68.24

func (a *AzureSpeech) Name() string

Name returns "foundry", the provider id shared with Foundry: routing, preference pinning and option manifests key on it, not on the wire format.

func (*AzureSpeech) Synthesize added in v0.68.24

func (a *AzureSpeech) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize renders text through SSML and returns the requested container.

type AzureSpeechOpts added in v0.68.24

type AzureSpeechOpts struct {
	// Host is the resource's custom domain, e.g.
	// "myresource.cognitiveservices.azure.com" (no scheme). Required.
	Host string
	// APIKey is the resource key, sent as Ocp-Apim-Subscription-Key.
	APIKey string
	// BearerToken, when set, wins over APIKey: it is called per request and
	// the token rides "Authorization: Bearer". Hosts set it for Entra sign-in.
	BearerToken speechkit.BearerTokenFunc
	// Voice is a Speech voice short name such as "de-DE-Mia:MAI-Voice-2" or
	// "en-US-Ethan:MAI-Voice-2-Flash"; defaults to "en-US-Harper:MAI-Voice-2".
	Voice string
	// Style is an optional mstts:express-as style ("friendly", "whispering").
	Style string
	// StyleDegree scales Style (0.01–2); only emitted together with Style.
	StyleDegree float64
}

AzureSpeechOpts configures the Azure Speech (MAI-Voice) TTS provider.

type AzureSpeechVoice added in v0.68.24

type AzureSpeechVoice struct {
	ShortName        string
	DisplayName      string
	LocalName        string
	Locale           string
	Gender           string
	VoiceType        string
	Status           string
	Styles           []string
	ModelSeries      string
	SecondaryLocales []string
	SampleRateHertz  int
}

AzureSpeechVoice is one entry of the resource's voices list.

type CapabilityReporter added in v0.46.0

type CapabilityReporter interface {
	Capabilities() []speechkit.Capability
}

CapabilityReporter is an optional interface a provider can implement to self-describe its capabilities, so routing can query them instead of string-matching profile IDs. It is intentionally NOT part of Provider, so existing implementations and test doubles are unaffected.

type Deepgram added in v0.46.0

type Deepgram struct {
	BaseURL    string
	Validation netsec.ValidationOptions
	// contains filtered or unexported fields
}

Deepgram implements Provider using the Deepgram Aura-2 text-to-speech REST API (POST /v1/speak). It reuses the Deepgram API key shared with the STT and Voice Agent adapters. Aura voices are selected via the model id (e.g. "aura-2-thalia-en"); there is no separate voice parameter.

Aura REST caps a single request at 2000 characters, so longer text is split on sentence/word boundaries. Raw concatenation is correct for streaming codecs (mp3, linear16/pcm, ogg-opus). WAV is handled specially: a multi-chunk WAV request is fetched as linear16 PCM and the joined PCM is wrapped in a single RIFF header (see encodeWAV), so the result is always one valid WAV.

func NewDeepgram added in v0.46.0

func NewDeepgram(opts DeepgramOpts) *Deepgram

NewDeepgram creates a Deepgram Aura TTS provider.

func (*Deepgram) CloseIdleConnections added in v0.46.0

func (d *Deepgram) CloseIdleConnections()

CloseIdleConnections drops idle keep-alive connections in the provider's HTTP client. It is safe on a nil receiver.

func (*Deepgram) Health added in v0.46.0

func (d *Deepgram) Health(ctx context.Context) error

Health synthesizes a one-word mp3 clip, which is a billable request; it fails fast when no API key is configured.

func (*Deepgram) Kind added in v0.46.0

func (d *Deepgram) Kind() ProviderKind

Kind reports ProviderKindDirectProvider: Deepgram's own API.

func (*Deepgram) Name added in v0.46.0

func (d *Deepgram) Name() string

Name returns "deepgram".

func (*Deepgram) Synthesize added in v0.46.0

func (d *Deepgram) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize renders text with Aura. The voice is the resolved Voice option, else the configured Model, else a locale default (German locales get a German voice); Format selects mp3 (default), wav, pcm/linear16 or opus, all at 24 kHz. Text beyond the Aura per-request limit is split on sentence boundaries and the chunks joined; multi-chunk WAV is fetched as PCM and re-wrapped in one header. It fails on empty text, a missing API key, an endpoint that fails validation, a transport error, or a non-200 response.

func (*Deepgram) SynthesizePCMStream added in v0.79.15

func (d *Deepgram) SynthesizePCMStream(ctx context.Context, text string, opts SynthesizeOpts, sampleRate int, emit func(pcm []byte) error) (bool, error)

SynthesizePCMStream implements PCMStreamer: Aura streams raw 16-bit PCM at its native 24 kHz while it renders, so playback can start after the first bytes instead of the whole clip. Another rate, an empty text, a missing key and the English Flux voices (a socket protocol of their own) are not streamed.

type DeepgramFluxTTS added in v0.54.10

type DeepgramFluxTTS struct {
	BaseURL    string
	Validation netsec.ValidationOptions
	// contains filtered or unexported fields
}

DeepgramFluxTTS opens Flux TTS streams. It reuses the Deepgram API key shared with the STT and Voice Agent adapters.

func NewDeepgramFluxTTS added in v0.54.10

func NewDeepgramFluxTTS(apiKey string) *DeepgramFluxTTS

NewDeepgramFluxTTS creates a Flux TTS client.

func (*DeepgramFluxTTS) Open added in v0.54.10

Open dials the Flux TTS WebSocket.

type DeepgramOpts added in v0.46.0

type DeepgramOpts struct {
	APIKey string
	Model  string // Aura-2 voice id, e.g. "aura-2-thalia-en"; empty => locale default
}

DeepgramOpts configures the Deepgram Aura TTS provider.

type EnabledProviders added in v0.46.0

type EnabledProviders struct {
	OpenAI *OpenAIOpts
	Google *GoogleOpts
	// Gemini registers Gemini API speech (Gemini 3.8 TTS) as the "gemini"
	// provider; hosts enable it instead of Google on the same Gemini key.
	Gemini      *GeminiOpts
	Deepgram    *DeepgramOpts
	HuggingFace *HuggingFaceOpts
	Foundry     *FoundryOpts
	// XAI registers xAI Grok Voice speech as the opt-in "xai" provider; a host
	// sets it only for a user who explicitly selected xAI speech output with
	// their own XAI_API_KEY. It is never a default: BuildRouter registers it
	// after every other provider, so only an explicit PreferredProfileID moves
	// it ahead of them.
	XAI *XAIOpts
	// FoundrySpeech routes Foundry speech output to the resource's Azure
	// Speech surface (MAI-Voice) instead of the OpenAI-compatible route. Both
	// adapters report the shared "foundry" provider id, so a host enables one
	// of Foundry / FoundrySpeech, not both.
	FoundrySpeech *AzureSpeechOpts
	Piper         *PiperOpts
	// SherpaPiper registers the bundled on-device Piper voices (German and
	// English) that run through the speechkit-tts-sherpa sidecar. A fresh
	// install enables it with no key.
	SherpaPiper *SherpaPiperOpts
	// SelfHostedOpenAI registers an operator-run OpenAI-compatible TTS server
	// (Kokoro-FastAPI, Speaches) as the "kokoro" Local Provider.
	SelfHostedOpenAI *SelfHostedOpenAIOpts
	// PreferredProfileID optionally pins the provider matching this
	// model_selection profile to the front of the strategy order.
	PreferredProfileID string
}

EnabledProviders carries the per-provider options a host has already resolved from its own config (env secrets, model/voice defaults). Nil fields are skipped. It lets the Device- and Server-Targets share one router-assembly path (BuildRouter) while each keeps its own config-resolution specifics.

type FluxSpeechEvent added in v0.54.10

type FluxSpeechEvent struct {
	// Audio holds raw linear16 PCM at the negotiated sample rate.
	Audio []byte
	// Type is the control event name (SpeechStarted, SpeechMetadata, Interrupt).
	Type string
	// SpeechID identifies the turn this event belongs to.
	SpeechID string
	// AudioDurationMs is the synthesized duration reported with SpeechMetadata.
	AudioDurationMs int64
	// InputCharacterCount and BillableCharacterCount close out the turn's
	// billing, reported with SpeechMetadata.
	InputCharacterCount    int
	BillableCharacterCount int
	// TextSpoken and TextRemaining are reported on Interrupt: what the listener
	// actually heard before the barge-in, and what was cut. Recording
	// TextSpoken as the assistant turn keeps the conversation history honest.
	TextSpoken    string
	TextRemaining string
	// Raw is the undecoded control frame. Flux TTS is young and its event
	// payloads are not fully documented, so keeping the original lets callers
	// read fields this client does not model yet.
	Raw json.RawMessage
}

FluxSpeechEvent is one decoded event from a Flux TTS stream. Exactly one of Audio or Type is populated: binary frames carry Audio, control frames carry Type and the fields belonging to it.

func (FluxSpeechEvent) IsAudio added in v0.54.10

func (e FluxSpeechEvent) IsAudio() bool

IsAudio reports whether the event carries synthesized audio.

type FluxSpeechOptions added in v0.54.10

type FluxSpeechOptions struct {
	// Voice is a Flux TTS model id such as "flux-kit-en". Empty uses
	// DeepgramFluxTTSDefaultVoice.
	Voice string
	// SampleRateHz selects the linear16 output rate. Zero uses Deepgram's
	// default of 24 kHz, which matches SpeechKit's playback contract.
	SampleRateHz int
	// Speed snaps to the nearest value Flux accepts (0.5–1.5 in 0.05 steps).
	// Zero keeps the provider default.
	Speed float64
	// Expressivity sets the calm-to-animated range, -2 to 2; zero keeps the
	// voice's tuned delivery. It is fixed for the connection and a beta
	// control: non-zero values raise the risk of pronunciation errors.
	Expressivity int
}

FluxSpeechOptions configures a Flux TTS stream.

type FluxSpeechStream added in v0.54.10

type FluxSpeechStream struct {
	// contains filtered or unexported fields
}

FluxSpeechStream is a live Flux TTS connection.

func (*FluxSpeechStream) Close added in v0.54.10

func (s *FluxSpeechStream) Close() error

Close shuts the stream down. It is safe to call more than once.

func (*FluxSpeechStream) Configure added in v0.54.10

func (s *FluxSpeechStream) Configure(ctx context.Context, speed float64) error

Configure adjusts the delivery speed mid-stream without reconnecting.

func (*FluxSpeechStream) Flush added in v0.54.10

func (s *FluxSpeechStream) Flush(ctx context.Context) error

Flush ends the turn so the server synthesizes whatever text is buffered.

func (*FluxSpeechStream) Receive added in v0.54.10

Receive returns the next audio frame or control event, and io.EOF when Deepgram closes the stream.

func (*FluxSpeechStream) SampleRateHz added in v0.54.10

func (s *FluxSpeechStream) SampleRateHz() int

SampleRateHz reports the linear16 output rate.

func (*FluxSpeechStream) Speak added in v0.54.10

func (s *FluxSpeechStream) Speak(ctx context.Context, text string) error

Speak streams text into the current turn. Callers pass LLM tokens as they arrive; the server decides where to break for synthesis.

func (*FluxSpeechStream) Voice added in v0.54.10

func (s *FluxSpeechStream) Voice() string

Voice reports the Flux voice this stream negotiated.

type Foundry added in v0.67.5

type Foundry struct {
	BaseURL    string
	Validation netsec.ValidationOptions
	// contains filtered or unexported fields
}

Foundry implements Provider using the Microsoft Foundry OpenAI-compatible audio/speech API. BaseURL is the OpenAI-compatible base derived from the project endpoint (https://<host>/openai); the model is the deployment name.

Foundry's v1 surface accepts Bearer auth, so the API key rides the standard Authorization header. Validation is strict by default (public https only).

func NewFoundry added in v0.67.5

func NewFoundry(opts FoundryOpts) *Foundry

NewFoundry creates a Microsoft Foundry TTS provider.

func (*Foundry) CloseIdleConnections added in v0.67.5

func (f *Foundry) CloseIdleConnections()

CloseIdleConnections drops idle keep-alive connections in the provider's HTTP client. It is safe on a nil receiver.

func (*Foundry) Health added in v0.67.5

func (f *Foundry) Health(ctx context.Context) error

Health synthesizes a one-word mp3 clip through the deployment, which is a billable request; it fails fast when neither an API key nor a bearer-token source is configured, or when BaseURL is empty.

func (*Foundry) Kind added in v0.67.5

func (f *Foundry) Kind() ProviderKind

Kind reports ProviderKindDirectProvider: the resource's own API.

func (*Foundry) Name added in v0.67.5

func (f *Foundry) Name() string

Name returns "foundry", the provider id shared with AzureSpeech.

func (*Foundry) Synthesize added in v0.67.5

func (f *Foundry) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize posts to the OpenAI-compatible audio/speech route with the deployment as model, the resolved voice (default "alloy"), the resolved format (wav, mp3, opus or pcm; anything else becomes mp3) and the speed clamped to 0.25–4.0. It fails on empty text, an empty BaseURL, an endpoint that fails validation, a bearer-token error, a transport error, or a non-200 response. The reported sample rate is 24 kHz.

type FoundryOpts added in v0.67.5

type FoundryOpts struct {
	APIKey string
	// BearerToken, when set, wins over APIKey: it is called per request and
	// the token rides "Authorization: Bearer". Hosts set it for Entra sign-in.
	BearerToken speechkit.BearerTokenFunc
	BaseURL     string // OpenAI-compatible base, e.g. https://<host>/openai (required)
	Model       string // deployment name; defaults to "gpt-4o-mini-tts"
	Voice       string // alloy, echo, fable, onyx, nova, shimmer; defaults to "alloy"
}

FoundryOpts configures the Microsoft Foundry TTS provider.

type Gemini added in v0.74.0

type Gemini struct {
	BaseURL    string
	Validation netsec.ValidationOptions
	// contains filtered or unexported fields
}

Gemini implements Provider using the Gemini API text-to-speech models (Gemini 3.8 Flash TTS and Flash-Lite TTS) through the unary Interactions endpoint. The unary response carries a complete 24 kHz mono 16-bit WAV; raw L16 PCM is wrapped in a WAV header so callers always get a playable file unless they asked for "pcm".

BaseURL is configurable for testing. It is validated against Validation on every request. Default Validation is strict (public https only).

func NewGemini added in v0.74.0

func NewGemini(opts GeminiOpts) *Gemini

NewGemini creates a Gemini API TTS provider.

func (*Gemini) CloseIdleConnections added in v0.74.0

func (g *Gemini) CloseIdleConnections()

CloseIdleConnections releases idle keep-alive connections of the provider's HTTP client.

func (*Gemini) Health added in v0.74.0

func (g *Gemini) Health(ctx context.Context) error

Health reports an error when no API key is configured; it makes no network call.

func (*Gemini) Kind added in v0.74.0

func (g *Gemini) Kind() ProviderKind

Kind implements Provider; the Gemini API is a direct cloud provider.

func (*Gemini) Name added in v0.74.0

func (g *Gemini) Name() string

Name implements Provider; it returns "gemini".

func (*Gemini) Synthesize added in v0.74.0

func (g *Gemini) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize renders text with the configured Gemini TTS model. The voice is the resolved Voice option, else the configured voice; a request locale is forwarded as the speech language. The result is WAV at 24 kHz unless Format is "pcm", in which case the WAV header is stripped. It fails on empty text, a missing API key, an endpoint that fails validation, a transport error, a non-200 response, or a response without inline audio.

type GeminiOpts added in v0.74.0

type GeminiOpts struct {
	APIKey string
	Model  string // GeminiTTSModelFlash or GeminiTTSModelFlashLite; empty => GeminiTTSDefaultModel
	Voice  string // prebuilt voice such as "Kore", "Puck", "Charon"; empty => GeminiTTSDefaultVoice
}

GeminiOpts configures the Gemini TTS provider.

type Google added in v0.46.0

type Google struct {
	BaseURL    string
	Validation netsec.ValidationOptions
	// contains filtered or unexported fields
}

Google implements Provider using the Google Cloud Text-to-Speech API.

BaseURL is configurable for testing. It is validated against Validation on every request. Default Validation is strict (public https only).

func NewGoogle added in v0.46.0

func NewGoogle(opts GoogleOpts) *Google

NewGoogle creates a Google Cloud TTS provider.

func (*Google) Capabilities added in v0.46.0

func (*Google) Capabilities() []speechkit.Capability

Capabilities implements CapabilityReporter; the opt-in Google Cloud Text-to-Speech provider reports speechkit.CapabilityTTS only.

func (*Google) CloseIdleConnections added in v0.46.0

func (g *Google) CloseIdleConnections()

CloseIdleConnections releases idle keep-alive connections of the provider's HTTP client.

func (*Google) Health added in v0.46.0

func (g *Google) Health(ctx context.Context) error

Health reports an error when no API key is configured; it makes no network call.

func (*Google) Kind added in v0.46.0

func (g *Google) Kind() ProviderKind

Kind implements Provider; Google is a direct cloud provider.

func (*Google) Name added in v0.46.0

func (g *Google) Name() string

Name implements Provider; it returns "google".

func (*Google) Synthesize added in v0.46.0

func (g *Google) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize implements Provider against the Google Cloud Text-to-Speech text:synthesize endpoint with the configured API key.

type GoogleOpts added in v0.46.0

type GoogleOpts struct {
	APIKey string
	Voice  string // e.g. "de-DE-Neural2-B", "en-US-Neural2-J"
}

GoogleOpts configures the Google TTS provider.

type HuggingFace added in v0.46.0

type HuggingFace struct {
	BaseURL    string
	Validation netsec.ValidationOptions
	// contains filtered or unexported fields
}

HuggingFace implements Provider using the HuggingFace Inference API with text-to-speech models (e.g. parler-tts).

BaseURL is configurable for testing. It is validated against Validation on every request. Default Validation is strict (public https only).

func NewHuggingFace added in v0.46.0

func NewHuggingFace(opts HuggingFaceOpts) *HuggingFace

NewHuggingFace creates a HuggingFace TTS provider.

func (*HuggingFace) Capabilities added in v0.46.0

func (*HuggingFace) Capabilities() []speechkit.Capability

Capabilities implements CapabilityReporter; HuggingFace reports speechkit.CapabilityTTS only.

func (*HuggingFace) CloseIdleConnections added in v0.46.0

func (h *HuggingFace) CloseIdleConnections()

CloseIdleConnections drops idle keep-alive connections in the provider's HTTP client. It is safe on a nil receiver.

func (*HuggingFace) Health added in v0.46.0

func (h *HuggingFace) Health(ctx context.Context) error

Health only checks that a token is configured; it makes no request.

func (*HuggingFace) Kind added in v0.46.0

func (h *HuggingFace) Kind() ProviderKind

Kind reports ProviderKindCloudProvider: a hosted platform that routes to models rather than a vendor's own API.

func (*HuggingFace) Name added in v0.46.0

func (h *HuggingFace) Name() string

Name returns "huggingface".

func (*HuggingFace) Synthesize added in v0.46.0

func (h *HuggingFace) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize posts text to the Inference API for the configured model. The resolved Voice, when set, is sent as a Parler-TTS voice description; otherwise a canned description for the resolved locale is used (none for "auto"). The result format follows the response Content-Type (flac when unrecognised) at a reported 24 kHz. It fails on empty text, a model id with unsafe characters, an endpoint that fails validation, a transport error, or a non-200 response.

type HuggingFaceOpts added in v0.46.0

type HuggingFaceOpts struct {
	Token string // HF API token
	Model string // Model ID, e.g. "Qwen/Qwen3-TTS-12Hz-1.7B-Base"
}

HuggingFaceOpts configures the HuggingFace TTS provider.

type OpenAI added in v0.46.0

type OpenAI struct {
	BaseURL    string
	Validation netsec.ValidationOptions
	// contains filtered or unexported fields
}

OpenAI implements Provider using the OpenAI TTS API.

BaseURL is configurable for testing. It is validated against Validation on every request. Default Validation is strict (public https only).

func NewOpenAI added in v0.46.0

func NewOpenAI(opts OpenAIOpts) *OpenAI

NewOpenAI creates an OpenAI TTS provider.

func (*OpenAI) Capabilities added in v0.46.0

func (*OpenAI) Capabilities() []speechkit.Capability

Capabilities implements CapabilityReporter; OpenAI reports speechkit.CapabilityTTS only.

func (*OpenAI) CloseIdleConnections added in v0.46.0

func (o *OpenAI) CloseIdleConnections()

CloseIdleConnections drops idle keep-alive connections in the provider's HTTP client. It is safe on a nil receiver.

func (*OpenAI) Health added in v0.46.0

func (o *OpenAI) Health(ctx context.Context) error

Health synthesizes a one-word mp3 clip, which is a billable request; it fails fast when no API key is configured.

func (*OpenAI) Kind added in v0.46.0

func (o *OpenAI) Kind() ProviderKind

Kind reports ProviderKindDirectProvider: OpenAI's own API.

func (*OpenAI) Name added in v0.46.0

func (o *OpenAI) Name() string

Name returns "openai".

func (*OpenAI) Synthesize added in v0.46.0

func (o *OpenAI) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize posts to /v1/audio/speech with the configured model, the resolved voice (default "nova"), the resolved format (wav, mp3, opus or pcm; anything else becomes mp3) and the speed clamped to 0.25–4.0. It fails on empty text, an endpoint that fails validation, a transport error, or a non-200 response. The reported sample rate is 24 kHz.

type OpenAIOpts added in v0.46.0

type OpenAIOpts struct {
	APIKey string
	Model  string // "gpt-4o-mini-tts" (default); legacy "tts-1"/"tts-1-hd" still dial
	Voice  string // alloy, ash, ballad, coral, echo, fable, onyx, nova, sage, shimmer, verse, marin, cedar
}

OpenAIOpts configures the OpenAI TTS provider.

type PCMStreamer added in v0.79.15

type PCMStreamer interface {
	SynthesizePCMStream(ctx context.Context, text string, opts SynthesizeOpts, sampleRate int, emit func(pcm []byte) error) (streamed bool, err error)
}

PCMStreamer is an optional Provider extension for live playback: it streams the speech as raw signed 16-bit little-endian mono PCM at sampleRate while the provider is still rendering it. streamed reports whether any audio was emitted; false with a nil error means this request cannot be streamed (another rate, an unsupported voice) and the caller uses Synthesize. Once audio was emitted an error fails the request: it is never retried.

type Piper added in v0.46.0

type Piper struct {
	// contains filtered or unexported fields
}

Piper implements Provider via the `piper` command-line binary. The binary writes a WAV PCM stream to stdout when invoked with

piper --model <voice.onnx> --output-raw < input.txt

or `--output_file -` for a WAV-wrapped stream. Phase 3 of the voice-companion roadmap uses Piper as the all-local TTS so the Voice-Companion can talk without any cloud key.

The implementation does NOT bundle voice models. Operators run `scripts/prepare-piper-voices.ps1` once to download the desired voices into PiperOpts.VoiceDir. Default voice maps to <VoiceDir>/ en_US-amy-medium.onnx; locale "de" looks up de_DE-thorsten-medium.

func NewPiper added in v0.46.0

func NewPiper(opts PiperOpts) (*Piper, error)

NewPiper validates the options and returns a ready Provider. The voice directory must already exist; missing voice models surface as a clear "voice file not found" error at Synthesize time, not at construction, so a missing en_DE voice does not prevent the provider from answering en_US requests.

func (*Piper) Capabilities added in v0.46.0

func (*Piper) Capabilities() []speechkit.Capability

Capabilities implements CapabilityReporter; Piper reports speechkit.CapabilityTTS only.

func (*Piper) Health added in v0.46.0

func (p *Piper) Health(ctx context.Context) error

Health verifies the piper binary can be located. Voice-model presence is not checked here — operators may have a partial set installed and we still want /readyz to be green for the locales they DO have. Synthesize surfaces missing-voice errors per request.

func (*Piper) Kind added in v0.46.0

func (*Piper) Kind() ProviderKind

Kind reports ProviderKindLocalBuiltIn: Piper runs as a local subprocess and needs no network.

func (*Piper) Name added in v0.46.0

func (*Piper) Name() string

Name returns the provider identifier.

func (*Piper) Probe added in v0.46.0

func (p *Piper) Probe(ctx context.Context, voice, locale string) (*Result, error)

Probe runs piper with a short test phrase to verify the binary and the requested voice work end-to-end. Returns the synthesized WAV bytes (small — a few seconds of speech) on success. Used by the Settings UI to preview a voice without persisting any text.

func (*Piper) Synthesize added in v0.46.0

func (p *Piper) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize runs the piper subprocess for one utterance. The returned Result.Audio is a complete RIFF/WAVE PCM blob suitable for direct playback or HTTP delivery.

type PiperOpts added in v0.46.0

type PiperOpts struct {
	// Binary is the absolute or PATH-relative `piper` executable.
	// Empty defaults to "piper" (must be on $PATH).
	Binary string

	// VoiceDir is the filesystem root containing the .onnx voice
	// model files. Required.
	VoiceDir string

	// DefaultVoices maps a locale code (e.g. "en", "de") to a
	// voice-model filename inside VoiceDir. Falls back to the en_US
	// Amy medium voice when an entry is missing.
	DefaultVoices map[string]string

	// Timeout caps the subprocess execution. Zero defaults to 30 s
	// — generous because Piper warm-load on CPU can take several
	// seconds for a first synthesis.
	Timeout time.Duration
}

PiperOpts configures the local Piper subprocess.

type PiperVoiceInfo added in v0.46.0

type PiperVoiceInfo struct {
	Filename string `json:"filename"`
	Locale   string `json:"locale"`  // short code, e.g. "en", "de"
	Region   string `json:"region"`  // e.g. "US", "DE"; empty when missing
	Name     string `json:"name"`    // e.g. "amy", "thorsten"
	Quality  string `json:"quality"` // e.g. "low", "medium", "high"
	SizeKB   int    `json:"size_kb"`
}

PiperVoiceInfo is one entry from a voice-directory scan. Filename is the basename inside VoiceDir (e.g. "en_US-amy-medium.onnx"). The remaining fields are best-effort parses of the rhasspy/piper-voices naming convention <lang>_<REGION>-<name>-<quality>.onnx; when the filename does not follow that pattern only Filename is populated and the other fields remain empty.

func ListPiperVoices added in v0.46.0

func ListPiperVoices(voiceDir string) ([]PiperVoiceInfo, error)

ListPiperVoices scans voiceDir for *.onnx files and parses each filename using the piper-voices naming convention. The list is sorted by Filename so callers can present a stable UI. Returns an empty slice (not an error) when voiceDir is empty or missing — the UI surfaces "no voices installed" rather than a hard error.

type Provider

type Provider interface {
	Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)
	Name() string
	Kind() ProviderKind
	Health(ctx context.Context) error
}

Provider defines the interface for text-to-speech backends.

func OrderByPreferredProvider

func OrderByPreferredProvider(providers []Provider, preferred string) []Provider

OrderByPreferredProvider returns providers with the matching provider first.

type ProviderKind

type ProviderKind string

ProviderKind identifies whether a provider is local, cloud-routed, or a direct external API. Router strategies use this instead of provider names.

const (
	// ProviderKindLocalBuiltIn runs on the device under SpeechKit's control
	// (the Piper subprocess) and needs no network at all.
	ProviderKindLocalBuiltIn ProviderKind = "local_built_in"
	// ProviderKindLocalProvider is a service the user runs on their own machine
	// or network, such as an OpenAI-compatible Kokoro/openedai-speech server.
	ProviderKindLocalProvider ProviderKind = "local_provider"
	// ProviderKindCloudProvider is a hosted inference platform that routes to
	// models (Hugging Face Inference) rather than a vendor's own API.
	ProviderKindCloudProvider ProviderKind = "cloud_provider"
	// ProviderKindDirectProvider is a vendor's own hosted API (OpenAI, Deepgram
	// Aura, Microsoft Foundry).
	ProviderKindDirectProvider ProviderKind = "direct_provider"
)

Provider kinds, from most to least local. The Router's "-only" strategies count the first two as local.

type ResolvedSynthesizeOptions added in v0.46.0

type ResolvedSynthesizeOptions struct {
	Locale    string
	Voice     string
	Speed     float64
	Format    string
	Effective provideropts.EffectiveOptions
}

ResolvedSynthesizeOptions is the provider-neutral view of one synthesis request after ResolveSynthesizeOptions has layered every option source. The scalar fields are the effective language, voice, speed multiplier and container format (empty or zero when nothing set them); Effective keeps the full option set with the source each value came from.

func ResolveSynthesizeOptions added in v0.46.0

func ResolveSynthesizeOptions(provider, profileID string, opts SynthesizeOpts, providerDefaults, providerOverrides provideropts.Values) ResolvedSynthesizeOptions

ResolveSynthesizeOptions resolves the options for one request against the provider's TTS option manifest (an empty manifest when none is registered; profileID is only stamped on the result). Precedence, lowest to highest: providerDefaults, opts.Options, providerOverrides merged with opts.ProviderOptions, then the request's own Locale, Voice, Speed (when positive) and Format. Options the manifest does not support are kept but reported at debug level.

type Result

type Result struct {
	Audio      []byte
	Format     string
	SampleRate int
	Duration   time.Duration
	Provider   string
	Voice      string
}

Result holds the output of a TTS synthesis.

type Router

type Router struct {

	// Logger receives this router's diagnostics. Nil falls back to
	// slog.Default() at log time.
	Logger *slog.Logger
	// contains filtered or unexported fields
}

Router selects and falls back between TTS providers.

func BuildRouter added in v0.46.0

func BuildRouter(strategy Strategy, enabled EnabledProviders) (router *Router, ok bool, notes []string)

BuildRouter is the single source of truth for assembling a TTS router from a set of enabled providers: it constructs each enabled provider in a stable order, applies optional model_selection pinning, and returns the router plus human-readable notes. ok is false (router nil) when nothing is enabled.

func NewRouter

func NewRouter(strategy Strategy, providers ...Provider) *Router

NewRouter creates a TTS router with the given strategy and providers.

func (*Router) CloseIdleConnections

func (r *Router) CloseIdleConnections()

CloseIdleConnections asks HTTP-backed providers to drop idle connection pools.

func (*Router) HealthCheck

func (r *Router) HealthCheck(ctx context.Context) map[string]error

HealthCheck returns health status for all providers.

func (*Router) ReadyHealthCheck added in v0.50.0

func (r *Router) ReadyHealthCheck(ctx context.Context) map[string]error

ReadyHealthCheck reports only providers eligible under the active routing strategy. A local-only router with cloud providers configured must not be advertised as ready when Synthesize would skip every one of them.

func (*Router) SetProviders

func (r *Router) SetProviders(providers ...Provider)

SetProviders replaces the provider list.

func (*Router) Synthesize

func (r *Router) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (res *Result, err error)

Synthesize tries each eligible provider until one succeeds. Per-provider option overrides (SynthesizeOpts.ProviderOptionsByProvider) are applied to the selected provider, and an OpenTelemetry span records strategy/provider.

func (*Router) SynthesizePCMStream added in v0.79.15

func (r *Router) SynthesizePCMStream(ctx context.Context, text string, opts SynthesizeOpts, sampleRate int, emit func(pcm []byte) error) (bool, error)

SynthesizePCMStream implements PCMStreamer for the provider Synthesize would try first. A provider that cannot stream the request, or fails before emitting audio, leaves the request to Synthesize and its fallback order.

type SelfHostedOpenAI added in v0.73.3

type SelfHostedOpenAI struct {
	// contains filtered or unexported fields
}

SelfHostedOpenAI is a Local Provider that speaks the OpenAI /v1/audio/speech API to a TTS server the operator runs on the same host or private network, such as Kokoro-FastAPI (Apache-2.0) or Speaches (MIT). It reports the provider id "kokoro", which the tts.openedai.* model_selection profiles pin. Plain HTTP and private addresses are allowed; no request leaves the operator's network unless BaseURL points outside it.

func NewSelfHostedOpenAI added in v0.73.3

func NewSelfHostedOpenAI(opts SelfHostedOpenAIOpts) (*SelfHostedOpenAI, error)

NewSelfHostedOpenAI validates opts and returns the provider.

func (*SelfHostedOpenAI) Health added in v0.73.3

func (s *SelfHostedOpenAI) Health(ctx context.Context) error

Health synthesizes a one-word clip against the local server.

func (*SelfHostedOpenAI) Kind added in v0.73.3

func (s *SelfHostedOpenAI) Kind() ProviderKind

Kind reports ProviderKindLocalProvider.

func (*SelfHostedOpenAI) Name added in v0.73.3

func (s *SelfHostedOpenAI) Name() string

Name returns "kokoro".

func (*SelfHostedOpenAI) Synthesize added in v0.73.3

func (s *SelfHostedOpenAI) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize posts to <BaseURL>/v1/audio/speech with the same option resolution as OpenAI.Synthesize and reports provider "kokoro".

type SelfHostedOpenAIOpts added in v0.73.3

type SelfHostedOpenAIOpts struct {
	// BaseURL is the server root, e.g. "http://speechkit-tts:8880"; a
	// trailing "/v1" is accepted and stripped. Required.
	BaseURL string
	// APIKey is sent as a bearer token when set; most local servers ignore it.
	APIKey string
	// Model defaults to "kokoro".
	Model string
	// Voice defaults to the Kokoro voice "af_bella".
	Voice string
	// RequireLocal rejects endpoints that resolve to a public address. Hosts
	// running a restricted network scope set it.
	RequireLocal bool
}

SelfHostedOpenAIOpts configures SelfHostedOpenAI.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is a small stable facade over Router. It gives embedders one construction point while still letting them provide their own providers.

func NewService

func NewService(router *Router, opts ...ServiceOption) (*Service, error)

NewService wraps router in a Service. It returns ErrMissingRouter when router is nil; nil options are ignored.

func (*Service) Router

func (s *Service) Router() *Router

Router returns the underlying Router, or nil for a nil Service.

func (*Service) Synthesize

func (s *Service) Synthesize(ctx context.Context, text string, opts ...SynthesizeOpts) (*Result, error)

Synthesize renders text through the underlying Router. At most one opts value is honoured: its non-zero scalar fields replace the service defaults and its option maps are merged over them (provider-keyed overrides replace per provider). A nil Service or missing router returns ErrMissingRouter.

type ServiceOption

type ServiceOption func(*Service)

ServiceOption customises a Service during NewService.

func WithDefaultOpts

func WithDefaultOpts(opts SynthesizeOpts) ServiceOption

WithDefaultOpts sets the SynthesizeOpts every Service.Synthesize call starts from; per-call options are merged on top of them.

type SherpaPiper added in v0.78.4

type SherpaPiper struct {
	// contains filtered or unexported fields
}

SherpaPiper speaks German and English on device through the speechkit-tts-sherpa sidecar. It needs no network and no API key. The sidecar starts on the first synthesis and stays up for the life of the provider.

func NewSherpaPiper added in v0.78.4

func NewSherpaPiper(opts SherpaPiperOpts) (*SherpaPiper, error)

NewSherpaPiper validates that the sidecar and the voice directory exist. The sidecar process starts on the first SherpaPiper.Synthesize or SherpaPiper.Health, not at construction, so a host that never speaks pays nothing.

func (*SherpaPiper) Close added in v0.78.4

func (s *SherpaPiper) Close()

Close stops the sidecar. A later synthesis starts a new one.

func (*SherpaPiper) Health added in v0.78.4

func (s *SherpaPiper) Health(ctx context.Context) error

Health starts the sidecar if it is not running and checks /health.

func (*SherpaPiper) Kind added in v0.78.4

func (*SherpaPiper) Kind() ProviderKind

Kind reports ProviderKindLocalBuiltIn: the sidecar and the voices run on this device and need no network.

func (*SherpaPiper) Name added in v0.78.4

func (*SherpaPiper) Name() string

Name returns ProviderSherpaPiper.

func (*SherpaPiper) Synthesize added in v0.78.4

func (s *SherpaPiper) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize returns a WAV of text spoken by the voice locale selects. German locales use Ramona; everything else uses LJSpeech.

type SherpaPiperOpts added in v0.78.4

type SherpaPiperOpts struct {
	// Binary is speechkit-tts-sherpa. Empty looks it up next to this process
	// and in the managed install locations, the same places the speech-to-text
	// sidecar is found.
	Binary string
	// VoicesDir is the models/tts directory holding both Piper VITS voices and
	// espeak-ng-data. Empty looks for models/tts next to the binary and this
	// process.
	VoicesDir string
	// Timeout caps one synthesis, including a cold start. Zero means 45 s.
	Timeout time.Duration
}

SherpaPiperOpts configures the bundled on-device TTS sidecar.

type Strategy

type Strategy string

Strategy determines how Router selects providers.

const (
	// StrategyCloudFirst is what [NewRouter] uses for an empty strategy; every
	// provider is eligible.
	StrategyCloudFirst Strategy = "cloud-first"
	// StrategyLocalFirst also admits every provider; local precedence has to
	// come from the host's provider order, not from the Router.
	StrategyLocalFirst Strategy = "local-first"
	// StrategyCloudOnly skips local built-in and local providers.
	StrategyCloudOnly Strategy = "cloud-only"
	// StrategyLocalOnly skips cloud and direct providers.
	StrategyLocalOnly Strategy = "local-only"
)

Routing strategies. The Router never reorders providers: the "-first" strategies admit every provider and try them in the order the host registered them (see BuildRouter); the "-only" strategies filter by ProviderKind.

type SynthesizeOpts

type SynthesizeOpts struct {
	Locale          string
	Voice           string
	Speed           float64
	Format          string
	Options         provideropts.Values
	ProviderOptions provideropts.Values
	// ProviderOptionsByProvider holds provider-keyed overrides that the Router
	// applies to the selected provider via ForProvider, so one request can
	// carry per-provider tuning without the caller knowing which provider wins.
	ProviderOptionsByProvider map[string]provideropts.Values
}

SynthesizeOpts configures a single TTS request.

func (SynthesizeOpts) ForProvider added in v0.46.0

func (o SynthesizeOpts) ForProvider(provider string) SynthesizeOpts

ForProvider returns a copy of opts with ProviderOptions merged from the provider-keyed overrides for the named provider. The Router calls this for the selected provider so per-provider tuning takes effect transparently.

type XAI added in v0.77.2

type XAI struct {
	BaseURL    string
	Validation netsec.ValidationOptions
	// contains filtered or unexported fields
}

XAI implements Provider using xAI's Grok Voice text-to-speech REST API (POST /v1/tts). It is an opt-in bring-your-own-key provider that reuses the XAI_API_KEY shared with the STT, Assist and Voice Agent adapters. A voice is a voice_id from GET /v1/tts/voices (every voice speaks every supported language) or a custom voice id; the API has no separate model parameter.

BaseURL is configurable for testing and validated against Validation on every request. Default Validation is strict (public https only).

func NewXAI added in v0.77.2

func NewXAI(opts XAIOpts) *XAI

NewXAI creates an xAI TTS provider.

func (*XAI) Capabilities added in v0.77.2

func (*XAI) Capabilities() []speechkit.Capability

Capabilities implements CapabilityReporter; the opt-in xAI Grok Voice provider reports speechkit.CapabilityTTS only.

func (*XAI) CloseIdleConnections added in v0.77.2

func (x *XAI) CloseIdleConnections()

CloseIdleConnections drops idle keep-alive connections in the provider's HTTP client. It is safe on a nil receiver.

func (*XAI) Health added in v0.77.2

func (x *XAI) Health(ctx context.Context) error

Health reports whether a key is configured and the API accepts it. It calls GET /v1/tts/voices, which is free, instead of synthesizing a billable clip.

func (*XAI) Kind added in v0.77.2

func (x *XAI) Kind() ProviderKind

Kind reports ProviderKindDirectProvider: xAI's own API.

func (*XAI) Name added in v0.77.2

func (x *XAI) Name() string

Name returns "xai".

func (*XAI) Synthesize added in v0.77.2

func (x *XAI) Synthesize(ctx context.Context, text string, opts SynthesizeOpts) (*Result, error)

Synthesize renders text with Grok Voice. The voice is the resolved Voice option, else the configured Voice, else "eve". Format selects mp3 (default), wav or pcm (raw signed 16-bit mono), all at 24 kHz; any other format, opus included, becomes mp3. The locale maps to the closest xAI language code, or "auto" when none fits. Speed is clamped to xAI's 0.7–1.5. It fails on empty text, text over xAI's 60,000-character limit, a missing API key, an endpoint that fails validation, a transport error, or a non-200 response.

type XAIOpts added in v0.77.2

type XAIOpts struct {
	APIKey string
	// Voice is a Grok voice_id such as "eve" (the default), "ara" or "rex".
	Voice string
}

XAIOpts configures the xAI TTS provider.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL