ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

基于 Google Cloud 语音识别与合成的实战指南:Chirp 3、Gemini TTS 与 Gemini 3.5 Transcribe 全解析

基于 Google Cloud 语音识别与合成的实战指南:Chirp 3、Gemini TTS 与 Gemini 3.5 Transcribe 全解析 基于 Google Cloud 语音识别与合成的实战指南Chirp 3、Gemini TTS 与 Gemini 3.5 Transcribe 全解析【免费下载链接】generative-aiSample code and notebooks for Generative AI on Google Cloud, with Gemini Enterprise Agent Platform项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai本文以 audio/speech/README.md 为索引骨架系统讲解 generative-ai 仓库中audio/speech目录下围绕 Google Cloud Speech-to-Text 与 Text-to-Speech 的完整实现涵盖 Chirp 3 转录批量、语言无关、说话人分离、流式、Gemini 3.5 Transcribe同步与 Live 流式、Chirp 3 HD 音色与 Gemini-TTS 合成提示词控情绪、双人对话、自定义音色克隆以及 storytelling 与多说话人播客两个落地用例。读完本文你将掌握两条 API 路线Cloud Speech/Text-to-Speech API 与 Agent Platform API的选型逻辑并能直接复用仓库中的可运行代码。目录总览识别与合成两条主线audio/speech目录围绕语音识别Speech Recognition与语音生成Speech Generation两条技术主线组织所有 Notebook 均可一键打开运行Getting Started入门系列逐一覆盖转录与合成两大 API 的入门实现。转录Speech-to-Textget_started_with_chirp_3_transcription.ipynbSpeech-to-Text API V2 Chirp 3、gemini_3_5_transcribe.ipynbAgent Platform Gemini 3.5 Transcribe同步与流式、gemini_3_5_transcribe_live.py真实麦克风实时转写脚本。合成Text-to-Speechget_started_with_chirp_3_hd_voices.ipynbChirp 3 HD 音色、get_started_with_gemini_tts_voices.ipynbGemini-TTS覆盖两条 API、gemini_3_1_flash_tts.ipynbAgent Platform 上的 Gemini 3.1 Flash TTS、get_started_with_chirp3_instant_custom_voice.ipynb即时自定义音色。Use Cases应用场景storytelling.ipynb用 Gemini 生成剧本、为每个角色分配不同音色并拼接为完整音频配套剧本数据 macbeth_the_sitcom.json。multi-speaker-podcast.ipynb从 PDF 生成双人对话式播客音频。说明README 早期索引的get_started_with_chirp_3.ipynb、get_started_with_chirp_2_sdk.ipynb已在仓库中演进为上述更细分的 Notebook本文以下内容均以仓库当前实际文件为准。通用前置条件项目、认证与 SDK所有 Notebook 的第一步几乎相同这也是运行任何示例前必须完成的公共环节# 项目 ID 优先从参数读取缺省时回退到环境变量 PROJECT_ID [your-project-id] # param {type: string, isTemplate: true} if not PROJECT_ID or PROJECT_ID [your-project-id]: PROJECT_ID str(os.environ.get(GOOGLE_CLOUD_PROJECT))Colab 环境内先做用户认证再设置配额项目import sys if google.colab in sys.modules: from google.colab import auth auth.authenticate_user()! gcloud config set project {PROJECT_ID} ! gcloud auth application-default set-quota-project {PROJECT_ID} ! gcloud auth application-default login -q依赖安装按 API 分三类# 1) Speech-to-Text API V2Chirp 3 转录 %pip install --upgrade --quiet google-cloud-speech ipywebrtc # 2) Text-to-Speech APIChirp 3 HD / Gemini-TTS要求版本 2.31.0 才能使用 Gemini-TTS 字段 %pip install --upgrade --quiet google-cloud-texttospeech # 3) Agent Platform 统一 SDKGemini 3.5 Transcribe / Gemini 3.1 Flash TTS %pip install --upgrade --quiet google-genai ipywebrtc soundfile numpy pydub需注意的两点约束区域可用性Chirp 3 转录与 Chirp 3 HD 音色均有区域限制需分别查阅官方文档确认可用区域后设置STT_LOCATION/TTS_LOCATION。认证模型google-cloud-speech、google-cloud-texttospeech走 gRPC/HTTP 的 API 端点 ADC 认证google-genai则通过genai.Client(enterpriseTrue, project..., location...)直接绑定项目与区域。一、语音识别从 Chirp 3 到 Gemini 3.5 Transcribe1.1 Chirp 3 TranscriptionSpeech-to-Text API V2get_started_with_chirp_3_transcription.ipynb 使用google.cloud.speech_v2.SpeechClient与google.cloud.speech_v2.types.cloud_speech展示四种识别模式。先创建客户端与 recognizer 常量STT_LOCATION us client SpeechClient( client_optionsClientOptions(api_endpointf{STT_LOCATION}-speech.googleapis.com) ) recognizer client.recognizer_path(PROJECT_ID, STT_LOCATION, _) model chirp_3 MAX_AUDIO_LENGTH_SECS 8 * 60 * 60 # 批量识别任务超时上限① 在线同步识别适用于时长小于 1 分钟的文件一次性返回完整结果。使用AutoDetectDecodingConfig让模型自动判断音频编码格式config cloud_speech.RecognitionConfig( auto_decoding_configcloud_speech.AutoDetectDecodingConfig(), modelmodel, language_codes[en-US], ) with open(audio_filename, rb) as f: audio_content f.read() request cloud_speech.RecognizeRequest(recognizerrecognizer, configconfig, contentaudio_content) response client.recognize(requestrequest) # 结果在 response.results 中每条取 alternatives[0].transcript② 语言无关转录将language_codes设为[auto]Chirp 3 会自动识别音频中的主导语言并转写这对多语言应用至关重要Notebook 中示例为西班牙语 wav音频文件存放在 Cloud Storage请求时通过uriaudio_gcs_uri而非content传入。注意uri是gs://开头的 GCS 路径示例中用字符串替换把 HTTPS URL 转成了 GCS URI。③ 说话人分离批量识别单声道音频中自动区分说话人。启用方式是在RecognitionConfig.features中设置diarization_config同时通过RecognitionOutputConfig.gcs_output_config指定结果写入的 GCS 目录再调用batch_recognize方法长任务、结果落盘 GCSconfig cloud_speech.RecognitionConfig( auto_decoding_configcloud_speech.AutoDetectDecodingConfig(), featurescloud_speech.RecognitionFeatures( diarization_configcloud_speech.SpeakerDiarizationConfig(), ), modelmodel, language_codes[en-US], ) files [cloud_speech.BatchRecognizeFileMetadata(uriaudio_gcs_uri)] request cloud_speech.BatchRecognizeRequest( recognizerrecognizer, configconfig, filesfiles, recognition_output_configcloud_speech.RecognitionOutputConfig( gcs_output_configcloud_speech.GcsOutputConfig(urigcs_output_folder), ), ) operation client.batch_recognize(requestrequest) response operation.result(timeoutMAX_AUDIO_LENGTH_SECS) transcript response.results[audio_gcs_uri].uriNotebook 还提供了group_utterances_by_speaker_from_file辅助函数用正则words:\s*(\[.*?\])从 GCS 下载的 output.json 中提取逐词结果每个词带speakerLabel再按说话人标签把词分组为连续话语输出结构化的{dialogue: [{speaker: ..., text: ...}]}。④ 流式识别用streaming_recognize模拟流式转写。核心是生成器create_streaming_requests第一个请求必须是携带StreamingRecognitionConfig的配置请求后续请求逐个携带音频分块Notebook 中CHUNK_SIZE 3200字节。音频可先用 ipywebrtc 的CameraStreamAudioRecorder录下麦克风输入再经 FFmpeg 转为 MP3。响应对response.results逐条打印中间结果最后拼接为完整转录文本。1.2 Gemini 3.5 TranscribeAgent Platformgemini_3_5_transcribe.ipynb 走 Agent Platform模型 ID 分别为MODEL_ID gemini-3.5-transcribe-preview # 同步generate_content MODEL_ID_LIVE gemini-3.5-transcribe-live-preview # 流式BidiGenerateContent Live同步场景的核心是把AudioTranscriptionConfig放进GenerateContentConfigresponse client.models.generate_content( modelMODEL_ID, contents[types.Part.from_bytes(dataaudio_bytes, mime_typeaudio/wav)], configtypes.GenerateContentConfig( audio_transcription_configtypes.AudioTranscriptionConfig( word_timestampTrue, ), ), )各同步能力与参数一一对应能力关键参数说明自动语言识别 词级时间戳word_timestampTrue每个词的start_offset/end_offset在audio_transcription.words中指定语言language_codes[es-ES]可传多个预期语言代码也演示了types.Part.from_uri(file_urigs://...)直接从 GCS 读取说话人分离diarizationTrue每个响应 part 的audio_transcription.speaker_label标记说话人自定义词表custom_vocabulary[oatmilk, oz]偏向识别特定产品名/品牌拼写同时指定语言时效果更可靠长音频AudioTranscriptionConfig()generate_content同步转写当前支持最长 1 小时音频流式场景使用client.aio.live.connect()异步 Live API构建LiveConnectConfigconfig types.LiveConnectConfig( response_modalities[TEXT], # 只回文本 input_audio_transcriptiontypes.AudioTranscriptionConfig(), # 也可加 language_codes / custom_vocabulary )Notebook 封装了三个复用助手send_streaming_audio用 soundfile 分块读文件、降混到单声道以audio/pcm;ratesample_rateMIME 通过session.send_realtime_input()发送结束后发audio_stream_endTruereceive_streaming_messages监听interim_input_transcription中间结果实时刷新显示与input_transcription定稿结果追加进缓冲streaming_main负责建立会话、等待setup_complete后并发跑收发两个协程。长音频流式转写采用会话分块策略Live 会话有实际时长上限因此用pydub把音频切成 2.5 分钟chunk_length_ms 150000的片段并保留前一片段末尾 500ms 重叠overlap_ms防止分界处断词每个片段开启独立 Live 会话逐块转写。真实麦克风实时转写见 gemini_3_5_transcribe_live.py它用sounddevice以 16kHz 单声道、0.1 秒块时长采集麦克风send_microphone_audio协程持续把 PCM 送入会话receive_streaming_messages用终端转义序列原位刷新中间结果、定稿结果另起一行输出。该脚本可直接运行pip install google-genai sounddevice certifi gcloud auth application-default login export GOOGLE_CLOUD_PROJECTyour-project-id python gemini_3_5_transcribe_live.py需注意单个 WebSocket 连接的生命周期约 10 分钟这是 Live API 连接的客观限制。二、语音合成Chirp 3 HD、Gemini-TTS 与即时自定义音色2.1 Chirp 3 HD VoicesText-to-Speech APIget_started_with_chirp_3_hd_voices.ipynb 介绍由 LLM 驱动的 Chirp 3 HD 音色高保真、自然停顿与拟人语调面向语音助手、有声书、客服等场景。当前提供8 个音色4 男 4 女、覆盖 31 种语言。音色名与语言拼接为形如en-US-Chirp3-HD-Aoede的完整名称VOICE Aoede # param [Aoede, Puck, Charon, Kore, Fenrir, Leda, Orus, Zephyr] LANGUAGE_CODE en-US # 如 de-DE / en-GB / en-IN / fr-FR / hi-IN / ja-JP / ko-KR / cmn-CN / ru-RU ... voice texttospeech.VoiceSelectionParams( namef{LANGUAGE_CODE}-Chirp3-HD-{VOICE}, language_codeLANGUAGE_CODE, )实时在线合成调用synthesize_speech输出 MP3 字节流response client.synthesize_speech( inputtexttospeech.SynthesisInput(textprompt), voicevoice, audio_configtexttospeech.AudioConfig(audio_encodingtexttospeech.AudioEncoding.MP3), ) display(Audio(response.audio_content))流式合成使用streaming_synthesize与转录相反它接收文本流、返回音频流。Notebook 的text_generator用正则[^.!?].!?把长文本按句切分以模拟流式输入synthesize_streaming先发携带StreamingSynthesizeConfig(voice...)的配置请求再逐句发StreamingSynthesisInput(text...)收到的音频块是 16-bit PCM用 NumPy 拼接后以 24000 Hz 采样率播放可打开display_individual_chunks逐块试听。2.2 Gemini-TTS双 API 路线与表达控制get_started_with_gemini_tts_voices.ipynb 讲解 Gemini-TTS 这一从自然走向可控的 TTS 演进30 个音色、80 locale可通过自然语言 prompt 精确指挥风格、口音、语速、语气甚至情绪表达。仓库示例使用的模型有gemini-3.1-flash-tts-preview、gemini-2.5-flash-tts、gemini-2.5-pro-tts。API 选型逻辑文档原文要点选Cloud Text-to-Speech API的情形已在用 Chirp 3 HD 或其他音色想平滑迁移需要特定音频编码Agent Platform 只输出 24kHz 16-bit PCM、无 WAV 头转换需客户端处理需要双向流式一个请求可配多次响应。选Agent Platform API的情形已从 AI Studio 使用 Gemini-TTS 想无缝切换到可扩展、合规的 Google Cloud已在用 Agent Platform 的其他模型统一 API 结构可降低接入成本。Cloud TTS API 路线SynthesisInput(text..., prompt...)同时携带文本与情绪指令。仓库演示了三种控制手段prompt 控情绪PROMPT You are having a conversation with a friend. Say the following in a happy and casual way配文本hahaha, i did NOT expect that...。prompt 控语速PROMPT Say the following very fast but still be intelligible。表达标签文本内嵌[chuckling]、[coughs]等修饰符非严格语法可自由实验如So.. [chuckling] tell me about this [coughs] AI thing.。双说话人对话通过MultiSpeakerVoiceConfig定义说话人别名到音色的映射输入支持两种结构multi_speaker_voice_config texttospeech.MultiSpeakerVoiceConfig( speaker_voice_configs[ texttospeech.MultispeakerPrebuiltVoice(speaker_aliasZizu, speaker_idFenrir), texttospeech.MultispeakerPrebuiltVoice(speaker_aliasGary, speaker_idOrus), ] ) # 方式一显式回合标记 multi_speaker_markup texttospeech.MultiSpeakerMarkup( turns[ texttospeech.MultiSpeakerMarkup.Turn(speakerZizu, textHave you tried the new multi-speaker feature on Gemini?), texttospeech.MultiSpeakerMarkup.Turn(speakerGary, textYes! I am super excited about it), ] ) # 方式二内联文本别名: 台词换行分隔 # textZizu: Have you tried...\nGary: Yes! ... response client.synthesize_speech( inputtexttospeech.SynthesisInput(multi_speaker_markupmulti_speaker_markup, promptPROMPT), voicetexttospeech.VoiceSelectionParams(language_codeen-gb, model_nameMODEL, multi_speaker_voice_configmulti_speaker_voice_config), audio_configtexttospeech.AudioConfig(audio_encodingtexttospeech.AudioEncoding.LINEAR16), )放宽安全过滤采用按月账单invoiced billing的账号可通过advanced_voice_optionstexttospeech.AdvancedVoiceOptions(relax_safety_filtersTrue)放宽有害内容过滤非此计费模式的账号该字段不可用。流式合成StreamingSynthesizeRequeststreaming_synthesize先发配置请求、文本发完后以半关闭half-close即生成器结束触发音频流开始返回。Notebook 实测打印了 time-to-first-audio 与 time-to-completion并提示真实 Web 场景应收到音频块立即emit(audio, response.audio_content)推给前端如 Flask-SocketIO。Agent Platform 路线genai.Client(enterpriseTrue, project..., location...)后通过client.models.generate_content的speech_config配置音色response client.models.generate_content( modelgemini-2.5-flash-tts, contentsTEXT, configtypes.GenerateContentConfig( speech_configtypes.SpeechConfig( language_codeen-in, voice_configtypes.VoiceConfig( prebuilt_voice_configtypes.PrebuiltVoiceConfig(voice_nameKore), ), ), ), ) data response.candidates[0].content.parts[0].inline_data.data # PCM 24kHz流式版用client.models.generate_content_stream同样逐块累积inline_data.data。由于 Agent Platform 返回的是无头 PCM仓库提供了wave_file(filename, pcm, channels1, rate24000, sample_width2)辅助函数补写 WAV 头以便播放。2.3 Gemini 3.1 Flash TTSAgent Platform 上的低延迟合成gemini_3_1_flash_tts.ipynb 聚焦 Agent Platform 上的 Gemini 3.1 Flash TTS低延迟、支持表达性音频标签。所有输出默认带 [SynthID] 水印。基本调用需同时设置response_modalities[AUDIO]与speech_configresponse client.models.generate_content( modelgemini-3.1-flash-tts-preview, contentsprompt, configtypes.GenerateContentConfig( response_modalities[AUDIO], speech_configtypes.SpeechConfig( voice_configtypes.VoiceConfig( prebuilt_voice_configtypes.PrebuiltVoiceConfig(voice_nameFenrir), ) ), ), ) # play_audio: np.frombuffer(inline_data.data, dtypei2)rate24000语言自动检测示例用西班牙语 prompt多说话人则通过MultiSpeakerVoiceConfigSpeakerVoiceConfig(speakerRyan, voice_config...)最多 2 个说话人且speaker名须与 prompt 中的名字一致。**音频标签Audio Tags**是该模型控制表达的核心形如[confusion]、[laughs]的方括号修饰词直接嵌入 prompt 即可调节风格、语气与节奏。仓库提供了一张常用标签表[determination]、[enthusiasm]、[adoration]、[interest]、[awe]、[nervousness]、[frustration]、[excitement]、[curiosity]、[whispers]、[laughs] 等另附约 200 个示例标签清单并特别提示即使转录文本是其他语言标签也用英文效果最佳。Notebook 还演示了用 Gemini 自动打标把长播客脚本连同标签清单交给gemini-3.7-flash要求在受影响的短语前插入标签、贴合叙事情绪弧线、避免过度使用再把打标后的脚本交给 TTS 模型合成。2.4 Chirp 3 Instant Custom Voice即时自定义音色get_started_with_chirp3_instant_custom_voice.ipynb 实现用录音即时训练个人音色支持流式与长文本输出、覆盖 25 语言。注意安全限制出于安全考虑该音色克隆能力仅对 allowlist 用户开放需联系 Google Cloud 团队开通。调用generateVoiceCloningKeyREST 端点创建音色 key需要参考音频推荐几秒清晰的 WAV与同意音频说话人明确读出同意脚本url fhttps://{API_ENDPOINT}/v1beta1/voices:generateVoiceCloningKey request_body { reference_audio: {audio_config: {audio_encoding: LINEAR16, sample_rate_hertz: 24000}, content: reference_audio_bytes}, # base64 voice_talent_consent: {audio_config: {audio_encoding: LINEAR16, sample_rate_hertz: 24000}, content: consent_audio_bytes}, consent_script: I am the owner of this voice and I consent to Google using this voice to create a synthetic voice model., language_code: en-US, } # 请求头需携带 Authorization: Bearer token 与 x-goog-user-project: PROJECT_ID # 响应中的 voiceCloningKey 即临时音色标识之后用text:synthesize端点、在voice.voice_clone.voice_cloning_key中携带该 key 合成文本音频编码 LINEAR16、24kHz。Notebook 最后用 Gradio 搭建了交互 App上传参考/同意音频 → Create Voicecreate_voice_with_masking对 key 做脱敏显示→ 输入文本 → Generate Speech并提供了 Google 风格化 CSSapp.launch(shareTrue)即可分享使用。三、落地用例多角色故事与双人播客3.1 storytelling多角色剧本配音storytelling.ipynb 完整走通写剧本 → 分角色 → 逐句合成 → 拼接 WAV流水线用 Gemini 生成剧本PROMPT Write an interesting and humorous version of the full play Macbeth by William Shakespeare.通过GenerateContentConfig(system_instruction..., response_mime_typeapplication/json, response_schemaStory)强制输出符合 Pydantic 模型的 JSON也可直接加载仓库预生成剧本 macbeth_the_sitcom.json。create_character_map为每个角色从 Gemini TTS 音色表中分配独立音色。关键限制与解法Gemini TTS 单次最多 2 个说话人因此用ThreadPoolExecutor把每一句台词按角色音色并行合成再按剧本顺序拼接combine_audio_clipswave_bytes包 WAV 头最终输出标题-complete.wav。3.2 multi-speaker-podcast从 PDF 到双人播客multi-speaker-podcast.ipynb 演示内容型播客生成先让 Gemini 总结 PDF示例为 arXiv 的 Attention Is All You Need 论文按R: [dialogue]/S: [dialogue]格式生成均衡双人对话稿随后把完整对话一次性交给gemini-3.1-flash-tts-preview用MultiSpeakerVoiceConfig将说话人 R/S 分别映射到Kore与Achird音色最终输出 WAV。该模式可直接复用于访谈、互动故事、游戏配音、E-learning 与无障碍场景。小结围绕audio/speech目录可以沉淀出三条可直接上手的工程路径识别侧用 Speech-to-Text API V2 的 Chirp 3批量/流式/说话人分离处理传统转写用 Agent Platform 的 Gemini 3.5 Transcribe 获得时间戳、自定义词表与实时 Live 能力合成侧用 Cloud TTS API 的 Chirp 3 HD 获取稳定高保真音色用 Gemini-TTS两条 API 皆可获取 prompt 级表达控制与双人对话进阶再叠加 Instant Custom Voice 音色克隆应用侧以 storytelling 与 multi-speaker-podcast 为模板搭建内容生产流水线。所有示例代码与配套数据均可在仓库对应路径直接打开复现配置时只需重点关注区域可用性、SDK 版本与各 API 的输入输出约束即可。【免费下载链接】generative-aiSample code and notebooks for Generative AI on Google Cloud, with Gemini Enterprise Agent Platform项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表