speech

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: BSD-2-Clause Imports: 36 Imported by: ? 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 speech provides Google Cloud's streaming speech services over gRPC: Speech-to-Text V2 streaming recognition (NewSTT), and Text-to-Speech streaming synthesis with Chirp 3 HD and Journey voices (NewTTS) and with Gemini TTS models (NewGeminiTTS). The Gemini service also runs on the Gemini API, with an API key in place of Google Cloud credentials.

They live apart from the gemini package, which holds the REST services that need only an HTTP client, because they are built on Google's gRPC clients for the two APIs: an application that imports gemini for its LLM does not link them.

Both authorize with Google Cloud credentials rather than an API key: a service-account key, given as its JSON or the path of its file, or a token source the application built itself. jargo reads no environment variables, so Application Default Credentials are opt-in through a token source:

creds, err := google.FindDefaultCredentials(ctx, speech.Scope) // x/oauth2/google
stt := speech.NewSTT(speech.STTConfig{
	ProjectID:   creds.ProjectID,
	Credentials: speech.Credentials{TokenSource: creds.TokenSource},
})

Index

Constants

View Source
const (
	// GeminiTTSSampleRate is the rate Gemini TTS models synthesize at.
	GeminiTTSSampleRate = 24000
)
View Source
const Scope = gcloud.Scope

Scope is the OAuth scope the speech APIs are authorized under. An application building its own token source should request it.

View Source
const StreamingLimit = 4 * time.Minute

StreamingLimit is how long one streaming recognition call is fed audio before it is replaced by another. Google ends a streaming call after five minutes, so the call is half-closed at four, its last results are read, and the next call carries on with the audio that arrived meanwhile.

Variables

View Source
var ErrNoCredentials = gcloud.ErrNoCredentials

ErrNoCredentials is returned when none of the ways to authorize was given.

View Source
var GeminiTTSVoices = []string{
	"Achernar", "Achird", "Algenib", "Algieba", "Alnilam", "Aoede", "Autonoe", "Callirrhoe", "Charon",
	"Despina", "Enceladus", "Erinome", "Fenrir", "Gacrux", "Iapetus", "Kore", "Laomedeia", "Leda",
	"Orus", "Puck", "Pulcherrima", "Rasalgethi", "Sadachbia", "Sadaltager", "Schedar", "Sulafat",
	"Umbriel", "Vindemiatrix", "Zephyr", "Zubenelgenubi",
}

GeminiTTSVoices are the prebuilt Gemini TTS voices. A voice outside the list is used anyway, with a warning, unless it is a custom voice from Voice design, whose id starts with "voice_".

Functions

This section is empty.

Types

type Credentials

type Credentials = gcloud.Credentials

Credentials says how to authorize against Google Cloud: a service-account key as JSON, the path of a key file, or a token source. It is the same type the gemini package's Text-to-Speech service takes, so one value serves both.

type GeminiTTSConfig added in v1.2.0

type GeminiTTSConfig struct {
	// APIKey is the Gemini API key. Given, it selects the Gemini API backend
	// unless UseGenAI says otherwise.
	APIKey string
	// UseGenAI selects the backend: true the Gemini API, false Cloud
	// Text-to-Speech. Nil selects the Gemini API when an API key is given.
	UseGenAI *bool
	// Credentials authorize the requests to Cloud Text-to-Speech. Required on
	// that backend.
	Credentials Credentials
	// Location is the Google Cloud location of a regional Cloud
	// Text-to-Speech endpoint (e.g. "us-central1"); empty uses the global one.
	Location string

	// Model is the Gemini TTS model, named as the chosen backend names it;
	// empty uses the backend's default.
	Model string
	// Voice is the voice name, one of GeminiTTSVoices or a custom voice id;
	// empty uses "Kore".
	Voice string
	// Language is the language spoken, mapped to a Google language code; the
	// zero value uses US English.
	Language language.Language
	// Prompt is the style instructions for how to synthesize the text.
	// Supported on Cloud Text-to-Speech, and on the Gemini API by Gemini 3.8
	// models; older models on the Gemini API ignore it, with a warning.
	Prompt string
	// MultiSpeaker synthesizes with the voices of SpeakerConfigs, on Cloud
	// Text-to-Speech only.
	MultiSpeaker bool
	// SpeakerConfigs are the speakers of a multi-speaker synthesis.
	SpeakerConfigs []SpeakerConfig `validate:"omitempty,dive"`
	// SampleRate is the PCM rate emitted downstream; 0 uses 24 kHz. Cloud
	// Text-to-Speech synthesizes Gemini voices at 24 kHz only, so another rate
	// may not work there; the Gemini API's audio is resampled to it.
	SampleRate int
}

GeminiTTSConfig configures the Gemini Text-to-Speech service, which synthesizes with Gemini's TTS models. It emits 16-bit mono PCM at the configured rate.

It runs on one of two backends. Cloud Text-to-Speech takes Google Cloud credentials and the models "gemini-3.1-flash-tts-preview" (the default), "gemini-2.5-flash-tts", "gemini-2.5-flash-lite-preview-tts" and "gemini-2.5-pro-tts". The Gemini API takes an API key and the models "gemini-3.8-flash-lite-tts" (the default), "gemini-3.8-flash-tts" and "gemini-3.1-flash-tts-preview".

Gemini 3.8 models on the Gemini API read the text as a verbatim transcript: the prompt is sent as the request's speech style, and only momentary vocal events belong in the text, as angle-bracket tags such as <laugh>, <sigh> and <short pause>. Older models take square-bracket markup tags such as [sigh] or [whispering] in the text instead.

func (GeminiTTSConfig) Validate added in v1.2.0

func (c GeminiTTSConfig) Validate() error

Validate reports whether the configuration is usable.

type GeminiTTSService added in v1.2.0

type GeminiTTSService struct {
	*tts.Base
}

GeminiTTSService is the Gemini text-to-speech service NewGeminiTTS builds.

func NewGeminiTTS added in v1.2.0

func NewGeminiTTS(cfg GeminiTTSConfig) *GeminiTTSService

NewGeminiTTS builds a Gemini Text-to-Speech service. Each sentence is synthesized on a streaming request, and its audio is passed on in half-second frames as it arrives.

type GeminiTTSSettings added in v1.2.0

type GeminiTTSSettings struct {
	settings.TTS

	// Prompt is the style instructions for how to synthesize the text.
	Prompt settings.Opt[string] `settings:"prompt"`
	// MultiSpeaker synthesizes with the voices of SpeakerConfigs.
	MultiSpeaker settings.Opt[bool] `settings:"multi_speaker"`
	// SpeakerConfigs are the speakers of a multi-speaker synthesis.
	SpeakerConfigs settings.Opt[[]SpeakerConfig] `settings:"speaker_configs"`
	// contains filtered or unexported fields
}

GeminiTTSSettings is the part of the Gemini synthesis configuration that can change while the pipeline runs. Each sentence is synthesized on a request of its own, so a change takes effect on the next one.

func (*GeminiTTSSettings) ApplyUpdate added in v1.2.0

func (s *GeminiTTSSettings) ApplyUpdate(delta any) (settings.Changed, error)

ApplyUpdate merges an update, implementing settings.Updater. A voice that is neither a prebuilt one nor a custom one is used anyway, with a warning, and so is a setting the Gemini API backend ignores.

type STTConfig

type STTConfig struct {
	// Credentials authorize the requests. Required.
	Credentials Credentials
	// ProjectID is the Google Cloud project the recognizer belongs to. Empty
	// takes the project_id of the service-account key; it is required with a
	// token source, which names no project.
	ProjectID string
	// Location is the Google Cloud location (e.g. "global", "us-central1",
	// "us"); empty uses "global". Any other location is served by its regional
	// endpoint.
	Location string
	// SampleRate is the input audio sample rate; 0 uses the transport's rate.
	SampleRate int

	// Languages are the languages to recognize, the first being the primary
	// one; empty recognizes US English.
	Languages []language.Language
	// Model is the recognition model; empty uses "latest_long".
	Model string
	// UseSeparateRecognitionPerChannel processes each audio channel separately.
	UseSeparateRecognitionPerChannel bool
	// EnableAutomaticPunctuation adds punctuation to transcripts; nil defaults
	// to true.
	EnableAutomaticPunctuation *bool
	// EnableSpokenPunctuation includes spoken punctuation in the transcript.
	EnableSpokenPunctuation bool
	// EnableSpokenEmojis includes spoken emojis in the transcript.
	EnableSpokenEmojis bool
	// ProfanityFilter filters profanity from the transcript.
	ProfanityFilter bool
	// EnableWordTimeOffsets includes timing information for each word.
	EnableWordTimeOffsets bool
	// EnableWordConfidence includes confidence scores for each word.
	EnableWordConfidence bool
	// EnableInterimResults streams partial recognition results; nil defaults
	// to true.
	EnableInterimResults *bool
	// EnableVoiceActivityEvents detects voice activity in the audio.
	EnableVoiceActivityEvents bool
	// Adaptation biases recognition toward specific words: a
	// *speechpb.SpeechAdaptation, or the equivalent map. Each "phrase_sets"
	// entry is either the resource name of a phrase set or an inline one:
	//
	//	map[string]any{"phrase_sets": []any{
	//		"projects/my-project/locations/global/phraseSets/catalog",
	//		map[string]any{"phrases": []any{map[string]any{"value": "jargo", "boost": 15.0}}},
	//	}}
	//
	// Referenced phrase sets must live in the same location as the service.
	// The telephony model rejects adaptation and transcribes without it;
	// support otherwise varies by model and language.
	Adaptation any
	// DenoiserConfig is background-noise removal: a *speechpb.DenoiserConfig,
	// or the equivalent map such as map[string]any{"denoise_audio": true}. Only
	// the Chirp 3 models denoise.
	DenoiserConfig any

	// TTFSP99 overrides the measured transcript latency the turn strategies
	// size their wait by; nil uses stt.GoogleTTFSP99, and zero means no wait.
	TTFSP99 *time.Duration
}

STTConfig configures the Google Cloud Speech-to-Text V2 streaming service. It is sent 16-bit mono PCM at the pipeline's input rate, or at SampleRate.

func (STTConfig) Validate

func (c STTConfig) Validate() error

Validate reports whether the configuration is usable: there are credentials, a project to address the recognizer by, and an adaptation and denoiser config Google's API can represent.

type STTService added in v1.0.0

type STTService struct {
	*stt.StreamService
}

STTService is the Google Cloud speech-to-text service NewSTT builds.

func NewSTT

func NewSTT(cfg STTConfig) *STTService

NewSTT builds a Google Cloud Speech-to-Text V2 streaming service.

Audio is streamed to Google over one streaming recognition call, which is replaced before Google's limit on a call's length (see StreamingLimit). A call that fails is reported and replaced a second later. A final result marks the end of the user's turn.

type STTSettings

type STTSettings struct {
	settings.STT

	// Languages are the languages to recognize, the first being the primary
	// one. An update giving a language replaces them with that language.
	Languages settings.Opt[[]language.Language] `settings:"languages"`
	// LanguageCodes are the languages to recognize as Google's own codes
	// (e.g. "en-US"), read only when Languages holds none.
	//
	// Deprecated: Use Languages, which take precedence. An update giving it is
	// warned about.
	LanguageCodes settings.Opt[[]string] `settings:"language_codes"`
	// UseSeparateRecognitionPerChannel processes each audio channel separately.
	UseSeparateRecognitionPerChannel settings.Opt[bool] `settings:"use_separate_recognition_per_channel"`
	// EnableAutomaticPunctuation adds punctuation to transcripts.
	EnableAutomaticPunctuation settings.Opt[bool] `settings:"enable_automatic_punctuation"`
	// EnableSpokenPunctuation includes spoken punctuation in the transcript.
	EnableSpokenPunctuation settings.Opt[bool] `settings:"enable_spoken_punctuation"`
	// EnableSpokenEmojis includes spoken emojis in the transcript.
	EnableSpokenEmojis settings.Opt[bool] `settings:"enable_spoken_emojis"`
	// ProfanityFilter filters profanity from the transcript.
	ProfanityFilter settings.Opt[bool] `settings:"profanity_filter"`
	// EnableWordTimeOffsets includes timing information for each word.
	EnableWordTimeOffsets settings.Opt[bool] `settings:"enable_word_time_offsets"`
	// EnableWordConfidence includes confidence scores for each word.
	EnableWordConfidence settings.Opt[bool] `settings:"enable_word_confidence"`
	// EnableInterimResults streams partial recognition results.
	EnableInterimResults settings.Opt[bool] `settings:"enable_interim_results"`
	// EnableVoiceActivityEvents detects voice activity in the audio.
	EnableVoiceActivityEvents settings.Opt[bool] `settings:"enable_voice_activity_events"`
	// Adaptation biases recognition toward specific words. See
	// STTConfig.Adaptation.
	Adaptation settings.Opt[any] `settings:"adaptation"`
	// DenoiserConfig is background-noise removal. See
	// STTConfig.DenoiserConfig.
	DenoiserConfig settings.Opt[any] `settings:"denoiser_config"`
}

STTSettings is the part of the Speech-to-Text configuration that can change while the pipeline runs. Google is told all of it when a streaming call opens, so a change to any of it reopens the session.

func (*STTSettings) ApplyUpdate

func (s *STTSettings) ApplyUpdate(delta any) (settings.Changed, error)

ApplyUpdate merges an update, implementing settings.Updater. Google reads the languages when a call opens, not the language, so a language the update gives replaces the languages rather than being stored.

type SpeakerConfig added in v1.2.0

type SpeakerConfig struct {
	// SpeakerAlias is the name the speaker goes by in the text.
	SpeakerAlias string `json:"speaker_alias"` //nolint:tagliatelle // the settings' wire name
	// SpeakerID is the voice the speaker speaks in; empty uses the configured
	// voice.
	SpeakerID string `json:"speaker_id,omitempty"` //nolint:tagliatelle // the settings' wire name
}

SpeakerConfig is one speaker of a multi-speaker synthesis.

type TTSConfig

type TTSConfig struct {
	// Credentials authorize the requests. Required.
	Credentials Credentials
	// Location is the Google Cloud location of a regional endpoint (e.g.
	// "us-central1"); empty uses the global endpoint.
	Location string
	// Voice is the voice name (e.g. "en-US-Chirp3-HD-Charon"); empty uses that
	// one.
	Voice string
	// Language is the language spoken, mapped to a Google language code; the
	// zero value uses US English.
	Language language.Language
	// SpeakingRate is the speaking rate, in the range [0.25, 2.0]; nil leaves
	// it to Google.
	SpeakingRate *float64
	// VoiceCloningKey selects a Chirp 3 custom voice; when set, it is used in
	// place of Voice.
	VoiceCloningKey string
	// SampleRate is the PCM rate requested and emitted downstream; 0 uses
	// 24 kHz.
	SampleRate int
}

TTSConfig configures the Google Cloud Text-to-Speech streaming service. It emits 16-bit mono PCM at the configured rate.

Only Chirp 3 HD and Journey voices synthesize over the streaming API. The gemini package's Text-to-Speech service, which synthesizes each sentence in one request, takes the others.

func (TTSConfig) Validate

func (c TTSConfig) Validate() error

Validate reports whether the configuration is usable.

type TTSService added in v1.0.0

type TTSService struct {
	*tts.Base
}

TTSService is the Google Cloud text-to-speech service NewTTS builds.

func NewTTS

func NewTTS(cfg TTSConfig) *TTSService

NewTTS builds a Google Cloud Text-to-Speech streaming service. Each sentence is synthesized on a streaming call, and its audio is passed on in half-second frames as it arrives.

type TTSSettings

type TTSSettings struct {
	settings.TTS

	// SpeakingRate is the speaking rate, in the range [0.25, 2.0]. No value
	// leaves it to Google.
	SpeakingRate settings.Opt[float64] `settings:"speaking_rate"`
}

TTSSettings is the part of the synthesis configuration that can change while the pipeline runs. Each sentence is synthesized on a streaming call of its own, so a change takes effect on the next one.

func (*TTSSettings) ApplyUpdate

func (s *TTSSettings) ApplyUpdate(delta any) (settings.Changed, error)

ApplyUpdate merges an update, implementing settings.Updater. A speaking rate outside the range Google accepts is refused with a warning: it stays as it was, while the rest of the update still applies.

Jump to

Keyboard shortcuts

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