본문으로 건너뛰기

Google

Mastra의 Google Voice 구현은 Google Cloud 서비스를 사용하여 텍스트 음성 변환(TTS) 및 음성 텍스트 변환(STT) 기능을 모두 제공합니다. 여러 음성, 언어, 고급 오디오 구성 옵션을 지원하고 표준 API 키 인증과 기업 배포를 위한 Vertex AI 모드를 모두 지원합니다.

사용예
사용예에 대한 직접 링크

import { GoogleVoice } from '@mastra/voice-google'

// Initialize with default configuration (uses GOOGLE_API_KEY environment variable)
const voice = new GoogleVoice()

// Text-to-Speech (plain text)
const audioStream = await voice.speak('Hello, world!', {
languageCode: 'en-US',
audioConfig: {
audioEncoding: 'LINEAR16',
},
})

// Text-to-Speech with SSML
const ssmlStream = await voice.speak('ignored', {
input: {
ssml: '<speak>Take <say-as interpret-as="unit">5 mg</say-as> daily.</speak>',
},
})

// Text-to-Speech with Gemini-TTS model
const geminiStream = await voice.speak('Hello from Gemini TTS!', {
voice: { name: 'Kore', modelName: 'gemini-2.5-flash-preview-tts' },
input: { prompt: 'Warm, calm tone.' },
})

// Speech-to-Text
const transcript = await voice.listen(audioStream, {
config: {
encoding: 'LINEAR16',
languageCode: 'en-US',
},
})

// Get available voices for a specific language
const voices = await voice.getSpeakers({ languageCode: 'en-US' })

생성자 매개변수
생성자 매개변수에 대한 직접 링크

speechModel?:

GoogleModelConfig
= { apiKey: process.env.GOOGLE_API_KEY }
Configuration for text-to-speech functionality
GoogleModelConfig

apiKey?:

string
Google Cloud API key. Falls back to GOOGLE_API_KEY environment variable. Not used when vertexAI is true.

keyFilename?:

string
Path to service account JSON key file. Falls back to GOOGLE_APPLICATION_CREDENTIALS environment variable.

credentials?:

object
In-memory service account credentials object with client_email and private_key properties.

listeningModel?:

GoogleModelConfig
= { apiKey: process.env.GOOGLE_API_KEY }
Configuration for speech-to-text functionality
GoogleModelConfig

apiKey?:

string
Google Cloud API key. Falls back to GOOGLE_API_KEY environment variable. Not used when vertexAI is true.

keyFilename?:

string
Path to service account JSON key file. Falls back to GOOGLE_APPLICATION_CREDENTIALS environment variable.

credentials?:

object
In-memory service account credentials object with client_email and private_key properties.

speaker?:

string
= 'en-US-Casual-K'
Default voice ID to use for text-to-speech

vertexAI?:

boolean
= false
Enable Vertex AI mode for enterprise deployments. Uses project-based authentication instead of API keys. Requires 'project' to be set.

project?:

string
Google Cloud project ID (required when vertexAI is true). Falls back to GOOGLE_CLOUD_PROJECT environment variable.

location?:

string
= 'us-central1'
Google Cloud region for Vertex AI. Falls back to GOOGLE_CLOUD_LOCATION environment variable.

행동 양식
행동 양식에 대한 직접 링크

speak()
speak에 대한 직접 링크

Google Cloud Text-to-Speech 서비스를 사용하여 텍스트를 음성으로 변환합니다.

input:

string | NodeJS.ReadableStream
Text to convert to speech. If a stream is provided, it will be converted to text first.

options?:

object
Speech synthesis options
GoogleSpeakOptions

speaker?:

string
Voice ID to use for this request.

languageCode?:

string
Language code for the voice (e.g., 'en-US'). Defaults to the language code derived from the speaker ID, or 'en-US'.

input?:

ISynthesizeSpeechRequest['input']
Rich input object passed through to the Google Cloud TTS API. Supports ssml, markup, prompt (Gemini-TTS style steering), customPronunciations, and multiSpeakerMarkup. When provided without text, ssml, markup, or multiSpeakerMarkup, the positional input argument is used as the text field automatically.

voice?:

ISynthesizeSpeechRequest['voice']
Voice configuration merged on top of defaults (name and languageCode). Supports modelName (e.g., 'gemini-2.5-flash-preview-tts') and multiSpeakerVoiceConfig.

audioConfig?:

ISynthesizeSpeechRequest['audioConfig']
Audio configuration options from Google Cloud Text-to-Speech API.

보고:Promise<NodeJS.ReadableStream>

listen()
listen에 대한 직접 링크

Google Cloud Speech-to-Text 서비스를 사용하여 음성을 텍스트로 변환합니다. v1(기본값) 및 v2 API를 모두 지원합니다. v2 API는 자동 디코딩을 통해 AAC-in-MP4 오디오(iOS Safari)에 대한 지원을 추가합니다.

v1(기본값)
v1(기본값)에 대한 직접 링크

audioStream:

NodeJS.ReadableStream
Audio stream to transcribe

options?:

GoogleListenOptionsV1
v1 recognition options
GoogleListenOptionsV1

config?:

IRecognitionConfig
v1 recognition configuration from Google Cloud Speech-to-Text API

v2
v2에 대한 직접 링크

통과하다v2: true 를 사용하여 AAC-in-MP4(iOS Safari)와 같은 추가 오디오 형식을 지원하는 Cloud Speech-to-Text v2 API를 사용합니다.

v2recognize 호출은 IAM 인증을 사용하며 API 키만을 사용한 인증은 허용하지 않습니다. 다음에서 서비스 계정 자격 증명을 구성하세요: listeningModel (or set GOOGLE_APPLICATION_CREDENTIALS) and set GOOGLE_CLOUD_PROJECT 를 설정한 경우에도 인식기 경로를 확인할 수 있도록 vertexAI is not enabled.

import { GoogleVoice } from '@mastra/voice-google'

// v2 listen() requires service account credentials, not just GOOGLE_API_KEY.
// Set GOOGLE_CLOUD_PROJECT so the recognizer path can be resolved.
const voice = new GoogleVoice({
listeningModel: { keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS },
})

const transcript = await voice.listen(iosSafariAacStream, {
v2: true,
config: {
autoDecodingConfig: {},
},
})

:::notelisten({ v2: true }) fails with PERMISSION_DENIED on speech.recognizers.recognize when only GOOGLE_API_KEY 가 설정되어 있습니다. API 키 요청에는 OAuth ID가 포함되지 않으므로 roles/speech.client 를 사용자 계정에 부여해도 도움이 되지 않습니다. 요청에 제시된 서비스 계정에 역할을 부여해야 합니다. 이는 vertexAI setting; speak()그리고 v1listen()여전히 API 키만으로 작업합니다. :::

audioStream:

NodeJS.ReadableStream
Audio stream to transcribe

options:

GoogleListenOptionsV2
v2 recognition options
GoogleListenOptionsV2

v2:

true
Enables the v2 API path

config?:

v2.IRecognitionConfig
v2 recognition configuration. Defaults to auto-decoding with languageCodes: ['en-US'] and model: 'long'. Set autoDecodingConfig: {} to auto-detect the audio format, or use explicitDecodingConfig to specify an encoding like MP4_AAC, M4A_AAC, or MOV_AAC.

recognizer?:

string
v2 recognizer resource path. Defaults to projects/{project}/locations/global/recognizers/_ where {project} is resolved from the constructor project option, GOOGLE_CLOUD_PROJECT, or the client's default project.

보고:Promise<string>

getSpeakers()
getspeakers에 대한 직접 링크

각 노드에 다음이 포함된 사용 가능한 음성 옵션의 배열을 반환합니다.

voiceId:

string
Unique identifier for the voice

languageCodes:

string[]
List of language codes supported by this voice

isUsingVertexAI()
isusingvertexai에 대한 직접 링크

Vertex AI 모드가 사용 설정되었는지 확인합니다.

보고:boolean - true if using Vertex AI, false otherwise

getProject()
getproject에 대한 직접 링크

구성된 Google Cloud 프로젝트 ID를 가져옵니다.

보고:string | undefined - The project ID or undefined if not set

getLocation()
getlocation에 대한 직접 링크

구성된 Google Cloud 위치/지역을 가져옵니다.

보고:string - The location (default: 'us-central1')

입증
입증에 대한 직접 링크

Google Voice Provider는 두 가지 인증 방법을 지원합니다.

표준 모드(API 키)
표준 모드(API 키)에 대한 직접 링크

인증을 위해 Google Cloud API 키를 사용합니다. 커버speak() and v1 listen(). It does not cover listen({ v2: true })이며, IAM 인증을 사용하고 서비스 계정 자격 증명이 필요합니다(참조: v2).

// Using environment variable (GOOGLE_API_KEY)
const voice = new GoogleVoice()

// Using explicit API key
const voice = new GoogleVoice({
speechModel: { apiKey: 'your-api-key' },
listeningModel: { apiKey: 'your-api-key' },
speaker: 'en-US-Casual-K',
})

Vertex AI 모드(서비스 계정)
Vertex AI 모드(서비스 계정)에 대한 직접 링크

서비스 계정에 Google Cloud 프로젝트 기반 인증을 사용합니다. 프로덕션 및 엔터프라이즈 배포에 권장됩니다.

이익:

  • 보안 강화(코드에 API 키 없음)
  • IAM 기반 액세스 제어
  • 프로젝트 수준 청구 및 할당량
  • 감사 로깅
  • 엔터프라이즈 기능

구성 옵션:

// Using Application Default Credentials (ADC)
// Set GOOGLE_APPLICATION_CREDENTIALS and GOOGLE_CLOUD_PROJECT env vars
const voice = new GoogleVoice({
vertexAI: true,
project: 'your-gcp-project',
location: 'us-central1', // Optional, defaults to 'us-central1'
})

// Using service account key file
const voice = new GoogleVoice({
vertexAI: true,
project: 'your-gcp-project',
speechModel: {
keyFilename: '/path/to/service-account.json',
},
listeningModel: {
keyFilename: '/path/to/service-account.json',
},
})

// Using in-memory credentials
const voice = new GoogleVoice({
vertexAI: true,
project: 'your-gcp-project',
speechModel: {
credentials: {
client_email: 'service-account@project.iam.gserviceaccount.com',
private_key: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
},
},
})

필수 권한
필수 권한에 대한 직접 링크

IAM 역할
IAM 역할에 대한 직접 링크

텍스트 음성 변환의 경우:

  • roles/texttospeech.admin- 텍스트 음성 변환 관리자(전체 액세스)
  • roles/texttospeech.editor- 텍스트 음성 변환 편집기(생성 및 관리)
  • roles/texttospeech.viewer- 텍스트 음성 변환 뷰어(읽기 전용)

음성-텍스트의 경우:

  • roles/speech.client- 음성-텍스트 클라이언트

승인하다roles/speech.client 를 요청에서 자격 증명을 제시하는 서비스 계정에 부여합니다( keyFilename, credentials, or GOOGLE_APPLICATION_CREDENTIALS). This role is required for listen({ v2: true }) 에 명시적으로 부여해야 하며, Vertex AI 모드에만 부여해서는 안 됩니다. 사용자 계정에 부여해도 API 키만 사용하는 요청에는 아무런 효과가 없습니다. 이러한 요청에는 인증에 사용할 ID가 포함되지 않기 때문입니다.

OAuth 범위
OAuth 범위에 대한 직접 링크

동기식 텍스트 음성 변환 합성의 경우:

  • https://www.googleapis.com/auth/cloud-platform- Google Cloud Platform 서비스에 대한 전체 액세스 권한

긴 오디오 텍스트 음성 변환 작업의 경우:

  • locations.longAudioSynthesize- 긴 오디오 합성 작업 생성
  • operations.get- 작업 상태 가져오기
  • operations.list- 목록 작업

중요 사항
중요 사항에 대한 직접 링크

  1. 입증: Google Cloud API 키(표준 모드) 또는 서비스 계정 사용자 인증 정보(Vertex AI 모드)가 필요합니다.
  2. 환경 변수:
    • GOOGLE_API_KEY- 표준 모드용 API 키
    • GOOGLE_CLOUD_PROJECT- Vertex AI 모드의 프로젝트 ID
    • GOOGLE_CLOUD_LOCATION- Vertex AI 모드의 위치(기본값은 'us-central1')
    • GOOGLE_APPLICATION_CREDENTIALS- 서비스 계정 키 파일 경로
  3. 기본 음성은 다음과 같이 설정되어 있습니다.'en-US-Casual-K'.
  4. 텍스트 음성 변환 및 음성 텍스트 변환 서비스는 모두 LINEAR16을 기본 오디오 인코딩으로 사용합니다.
  5. 그만큼speak() 메서드는 Google Cloud Text-to-Speech API를 통해 고급 오디오 구성을 지원합니다.
  6. 그만큼listen() 메서드는 Google Cloud Speech-to-Text API를 통해 다양한 인식 구성을 지원합니다.
  7. listen({ v2: true })서비스 계정 사용자 인증 정보가 필요하며GOOGLE_CLOUD_PROJECT; it fails with PERMISSION_DENIED when only GOOGLE_API_KEY is set. speak() and v1 listen() work with an API key alone.
  8. 사용 가능한 음성은 다음을 사용하여 언어 코드별로 필터링할 수 있습니다.getSpeakers() method.
  9. Vertex AI 모드는 IAM 제어, 감사 로그, 프로젝트 수준 청구를 포함한 엔터프라이즈 기능을 제공합니다.