Chirp 3:即時自訂語音

Text-to-Speech 的即時自訂語音功能可讓使用者透過訓練模型,建立個人化語音模型,訓練時使用的音訊必須是自己錄製的高品質音訊。這項技術可快速生成個人語音,並透過 Cloud TTS API 使用個人語音來合成音訊,同時支援串流和長篇文字。

試用 Colab 筆記本 在 GitHub 中查看筆記本

支援的語言

即時自訂語音支援下列語言:

語言 BCP-47 代碼 同意聲明
阿拉伯文 (XA) ar-XA .أنا مالك هذا الصوت وأوافق على أن تستخدم Google هذا الصوت لإنشاء نموذج صوتي اصطناعي
孟加拉文 (印度) bn-IN আমি এই ভয়েসের মালিক এবং আমি একটি সিন্থেটিক ভয়েস মডেল তৈরি করতে এই ভয়েস ব্যবহার করে Google-এর সাথে সম্মতি দিচ্ছি।
中文 (中國) cmn-CN 我是此聲音的擁有者,並授權 Google 使用此聲音建立語音合成模型
英文 (澳洲) en-AU 我是這個聲音的擁有者,我同意 Google 用此聲音建立合成語音模型。
英文 (印度) en-IN 我是這個聲音的擁有者,我同意 Google 用此聲音建立合成語音模型。
英文 (英國) en-GB 我是這個聲音的擁有者,我同意 Google 用此聲音建立合成語音模型。
英文 (美國) en-US 我是這個聲音的擁有者,我同意 Google 用此聲音建立合成語音模型。
法文 (加拿大) fr-CA Je suis le propriétaire de cette voix et j'autorise Google à utiliser cette voix pour créer un modèle de voix synthétique.
法文 (法國) fr-FR Je suis le propriétaire de cette voix et j'autorise Google à utiliser cette voix pour créer un modèle de voix synthétique.
德文 (德國) de-DE Ich bin der Eigentümer dieser Stimme und bin damit einverstanden, dass Google diese Stimme zur Erstellung eines synthetischen Stimmmodells verwendet.
古吉拉特文 (印度) gu-IN હું આ વૉઇસનો માલિક છું અને સિન્થેટિક વૉઇસ મોડેલ બનાવવા માટે આ વૉઇસનો ઉપયોગ કરવાની Googleને સંમતિ આપું છું
北印度文 (印度) hi-IN मैं इस आवाज़ का मालिक हूँ और मैं सिंथेटिक आवाज़ मॉडल बनाने के लिए Google को इस आवाज़ का उपयोग करने की सहमति देता हूँ
印尼文 (印尼) id-ID Saya adalah pemilik suara ini dan saya menyetujui Google menggunakan suara ini untuk membuat model suara sintetis.
義大利文 (義大利) it-IT Sono il proprietario di questa voce e acconsento che Google la utilizzi per creare un modello di voce sintetica.
日文 (日本) ja-JP 私はこの音声の所有者であり、Googleがこの音声を使用して音声合成モデルを作成することを承認します。
卡納達文 (印度) kn-IN ನಾನು ಈ ಧ್ವನಿಯ ಮಾಲಿಕ ಮತ್ತು ಸಂಶ್ಲೇಷಿತ ಧ್ವನಿ ಮಾದರಿಯನ್ನು ರಚಿಸಲು ಈ ಧ್ವನಿಯನ್ನು ಬಳಸಿಕೊಂಡುಗೂಗಲ್ ಗೆ ನಾನು ಸಮ್ಮತಿಸುತ್ತೇನೆ.
韓文 (韓國) ko-KR 我擁有這段語音的著作權,並允許 Google 使用這段語音建立語音合成模型。
馬拉雅拉姆文 (印度) ml-IN ഈ ശബ്ദത്തിന്റെ ഉടമ ഞാനാണ്, ഒരു സിന്തറ്റിക് വോയ്‌സ് മോഡൽ സൃഷ്ടിക്കാൻ ഈ ശബ്‌ദം ഉപയോഗിക്കുന്നതിന് ഞാൻ Google-ന് സമ്മതം നൽകുന്നു."
馬拉地文 (印度) mr-IN मी या आवाजाचा मालक आहे आणि सिंथेटिक व्हॉइस मॉडेल तयार करण्यासाठी हा आवाज वापरण्यासाठी मी Google ला संमती देतो
荷蘭文 (荷蘭) nl-NL Ik ben de eigenaar van deze stem en ik geef Google toestemming om deze stem te gebruiken om een synthetisch stemmodel te maken.
波蘭文 (波蘭) pl-PL Jestem właścicielem tego głosu i wyrażam zgodę na wykorzystanie go przez Google w celu utworzenia syntetycznego modelu głosu.
葡萄牙文 (巴西) pt-BR Eu sou o proprietário desta voz e autorizo o Google a usá-la para criar um modelo de voz sintética.
俄文 (俄羅斯) ru-RU Я являюсь владельцем этого голоса и даю согласие Google на использование этого голоса для создания модели синтетического голоса.
泰米爾文 (印度) ta-IN நான் இந்த குரலின் உரிமையாளர் மற்றும் செயற்கை குரல் மாதிரியை உருவாக்க இந்த குரலை பயன்படுத்த குகல்க்கு நான் ஒப்புக்கொள்கிறேன்.
泰盧固文 (印度) te-IN నేను ఈ వాయిస్ యజమానిని మరియు సింతటిక్ వాయిస్ మోడల్ ని రూపొందించడానికి ఈ వాయిస్ ని ఉపయోగించడానికి googleకి నేను సమ్మతిస్తున్నాను.
泰文 (泰國) th-TH ฉันเป็นเจ้าของเสียงนี้ และฉันยินยอมให้ Google ใช้เสียงนี้เพื่อสร้างแบบจำลองเสียงสังเคราะห์
土耳其文 (土耳其) tr-TR Bu sesin sahibi benim ve Google'ın bu sesi kullanarak sentetik bir ses modeli oluşturmasına izin veriyorum.
越南文 (越南) vi-VN Tôi là chủ sở hữu giọng nói này và tôi đồng ý cho Google sử dụng giọng nói này để tạo mô hình giọng nói tổng hợp.
西班牙文 (西班牙) es-ES Soy el propietario de esta voz y doy mi consentimiento para que Google la utilice para crear un modelo de voz sintética.
西班牙文 (美國) es-US Soy el propietario de esta voz y doy mi consentimiento para que Google la utilice para crear un modelo de voz sintética.

地區可用性

即時自訂語音功能適用於下列 Google Cloud 區域:

Google Cloud 區域 支援的方法 發布準備完成度
global 創作、合成 不公開預先發布版
us 整合 不公開預先發布版
eu 整合 不公開預先發布版
asia-southeast1 整合 不公開預先發布版

支援的輸出格式

預設回應格式為 LINEAR16,但其他支援的格式包括:

API 方法 格式
streaming ALAW、MULAW、OGG_OPUS 和 PCM
batch ALAW、MULAW、MP3、OGG_OPUS 和 PCM

功能支援與限制

功能 支援 說明
SSML 用於個人化合成音訊的 SSML 標記
以文字為主的提示 實驗功能 使用標點符號、停頓和口語障礙,為文字轉語音功能加入自然流暢的語調和節奏。
時間戳記 字詞層級時間戳記
暫停代碼 在合成音訊中加入隨選暫停
配速控制 調整合成音訊的速度,範圍從 0.25 倍速到 2 倍速。
發音控制 使用國際音標或 X-SAMPA 語音編碼,自訂字詞或詞組的發音

使用 Chirp 3:即時自訂語音

以下各節將探討如何使用 Chirp 3:Text-to-Speech API 中的即時自訂語音功能。

  1. 錄製同意聲明:為遵守即時自訂語音的法律和道德規範,請以適當語言錄製同意聲明,並儲存為單聲道音訊檔案,長度最多 10 秒,且必須採用支援的音訊編碼。(我是這個聲音的擁有者,我同意 Google 用此聲音建立合成語音模型。)

  2. 錄製參考音訊:使用電腦麥克風錄製音訊,長度最多 10 秒,並以支援的音訊編碼格式儲存為單聲道音訊檔案。錄音時應避免背景噪音。在相同環境中錄製同意聲明和參考音訊。

  3. 儲存音訊檔案:將錄製的音訊檔案儲存在指定的 Cloud Storage 位置。

製作高品質參考音訊的指南

  • 音訊長度應盡量接近 10 秒,且噪音極少。 不過,音訊應包含自然停頓和節奏,而不是在 10 秒內塞入太多字詞。
  • 模型會模擬麥克風的音質,因此如果錄音音質模糊,輸出內容也會模糊。
  • 語音應充滿活力,且比最終輸出內容更具表現力。此外,語音的節奏也應與複製語音的節奏一致。舉例來說,如果參考音訊沒有自然停頓或中斷,複製的聲音就不擅長停頓。
  • 好的提示會比單調無趣的提示更興奮、更有活力,模型會根據這些線索複製這種能量。

支援的音訊編碼

系統支援下列輸入音訊編碼:

  • LINEAR16
  • PCM
  • MP3
  • M4A

使用 REST API 建立即時自訂語音

即時自訂語音會以語音複製金鑰的形式呈現,這是語音資料的文字字串表示法。

重要注意事項

以下是建立自訂語音時的幾項重要注意事項:

  • 語音複製金鑰儲存在用戶端,且每次要求都會提供,因此可建立的語音複製金鑰數量沒有上限。
  • 多個用戶端或裝置可同時使用相同的語音複製金鑰。
  • 每個專案每分鐘最多可建立 10 個語音複製金鑰。詳情請參閱「要求限制」。
  • 您無法使用自訂同意聲明指令碼取代預設指令碼。您必須使用「語言支援」中提供的同意聲明指令碼。
import requests, os, json

def create_instant_custom_voice_key(
    access_token, project_id, reference_audio_bytes, consent_audio_bytes
):
    url = "https://texttospeech.googleapis.com/v1beta1/voices:generateVoiceCloningKey"

    request_body = {
        "reference_audio": {
            # Supported audio_encoding values are LINEAR16, PCM, MP3, and M4A.
            "audio_config": {"audio_encoding": "LINEAR16"},
            "content": reference_audio_bytes,
        },
        "voice_talent_consent": {
            # Supported audio_encoding values are LINEAR16, PCM, MP3, and M4A.
            "audio_config": {"audio_encoding": "LINEAR16"},
            "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",
    }

    try:
        headers = {
            "Authorization": f"Bearer {access_token}",
            "x-goog-user-project": project_id,
            "Content-Type": "application/json; charset=utf-8",
        }

        response = requests.post(url, headers=headers, json=request_body)
        response.raise_for_status()

        response_json = response.json()
        return response_json.get("voiceCloningKey")

    except requests.exceptions.RequestException as e:
        print(f"Error making API request: {e}")
    except json.JSONDecodeError as e:
        print(f"Error decoding JSON response: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

使用 REST API,透過即時自訂語音合成語音

使用語音複製金鑰,透過 REST API 合成音訊。

import requests, os, json, base64
from IPython.display import Audio, display

def synthesize_text_with_cloned_voice(access_token, project_id, voice_key, text):
    url = "https://texttospeech.googleapis.com/v1beta1/text:synthesize"

    request_body = {
        "input": {
            "text": text
        },
        "voice": {
            "language_code": "en-US",
            "voice_clone": {
                "voice_cloning_key": voice_key,
            }
        },
        "audioConfig": {
            # Supported audio_encoding values are LINEAR16, PCM, MP3, and M4A.
            "audioEncoding": "LINEAR16",
        }
    }

    try:
        headers = {
            "Authorization": f"Bearer {access_token}",
            "x-goog-user-project": project_id,
            "Content-Type": "application/json; charset=utf-8"
        }

        response = requests.post(url, headers=headers, json=request_body)
        response.raise_for_status()

        response_json = response.json()
        audio_content = response_json.get("audioContent")

        if audio_content:
            display(Audio(base64.b64decode(audio_content), rate=24000))
        else:
            print("Error: Audio content not found in the response.")
            print(response_json)

    except requests.exceptions.RequestException as e:
        print(f"Error making API request: {e}")
    except json.JSONDecodeError as e:
        print(f"Error decoding JSON response: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

使用 Python 用戶端程式庫,透過即時自訂語音合成語音

本範例使用 Python 用戶端程式庫執行即時自訂語音合成作業,並使用已儲存至 voice_cloning_key.txt 檔案的語音複製金鑰。如要生成語音複製金鑰,請參閱「使用 REST API 建立即時自訂語音」。

from google.cloud import texttospeech
from google.cloud.texttospeech_v1beta1.services.text_to_speech import client


def perform_voice_cloning(
    voice_cloning_key: str,
    transcript: str,
    language_code: str,
    synthesis_output_path: str,
    tts_client: client.TextToSpeechClient,
) -> None:
  """Perform voice cloning and write output to a file.

  Args:
    voice_cloning_key: The voice cloning key.
    transcript: The transcript to synthesize.
    language_code: The language code.
    synthesis_output_path: The synthesis audio output path.
    tts_client: The TTS client to use.
  """
  voice_clone_params = texttospeech.VoiceCloneParams(
      voice_cloning_key=voice_cloning_key
  )
  voice = texttospeech.VoiceSelectionParams(
      language_code=language_code, voice_clone=voice_clone_params
  )
  request = texttospeech.SynthesizeSpeechRequest(
      input=texttospeech.SynthesisInput(text=transcript),
      voice=voice,
      audio_config=texttospeech.AudioConfig(
          audio_encoding=texttospeech.AudioEncoding.LINEAR16,
          sample_rate_hertz=24000,
      ),
  )
  response = tts_client.synthesize_speech(request)
  with open(synthesis_output_path, 'wb') as out:
    out.write(response.audio_content)
    print(f'Audio content written to file {synthesis_output_path}.')


if __name__ == '__main__':
  client = texttospeech.TextToSpeechClient()
  with open('voice_cloning_key.txt', 'r') as f:
    key = f.read()
  perform_voice_cloning(
      voice_cloning_key=key,
      transcript='Hello world!',
      language_code='en-US',
      synthesis_output_path='/tmp/output.wav',
      tts_client=client,
  )

使用 Python 用戶端程式庫,透過即時自訂聲音串流合成語音

本範例使用 Python 用戶端程式庫執行即時自訂語音串流合成,並使用儲存在 voice_cloning_key.txt 的語音複製金鑰。如要生成語音複製金鑰,請參閱「使用 REST API 建立即時自訂語音」。

import io
import wave
from google.cloud import texttospeech
from google.cloud.texttospeech_v1beta1.services.text_to_speech import client


def perform_voice_cloning_with_simulated_streaming(
    voice_cloning_key: str,
    simulated_streamed_text: list[str],
    language_code: str,
    synthesis_output_path: str,
    tts_client: client.TextToSpeechClient,
) -> None:
  """Perform voice cloning for a given reference audio, voice talent consent, and consent script.

  Args:
    voice_cloning_key: The voice cloning key.
    simulated_streamed_text: The list of transcripts to synthesize, where each
      item represents a chunk of streamed text. This is used to simulate
      streamed text input and is not meant to be representative of real-world
      streaming usage.
    language_code: The language code.
    synthesis_output_path: The path to write the synthesis audio output to.
    tts_client: The TTS client to use.
  """
  voice_clone_params = texttospeech.VoiceCloneParams(
      voice_cloning_key=voice_cloning_key
  )
  streaming_config = texttospeech.StreamingSynthesizeConfig(
      voice=texttospeech.VoiceSelectionParams(
          language_code=language_code, voice_clone=voice_clone_params
      ),
      streaming_audio_config=texttospeech.StreamingAudioConfig(
          audio_encoding=texttospeech.AudioEncoding.PCM,
          sample_rate_hertz=24000,
      ),
  )
  config_request = texttospeech.StreamingSynthesizeRequest(
      streaming_config=streaming_config
  )

  # Request generator. Consider using Gemini or another LLM with output
  # streaming as a generator.
  def request_generator():
    yield config_request
    for text in simulated_streamed_text:
      yield texttospeech.StreamingSynthesizeRequest(
          input=texttospeech.StreamingSynthesisInput(text=text)
      )

  streaming_responses = tts_client.streaming_synthesize(request_generator())
  audio_buffer = io.BytesIO()
  for response in streaming_responses:
    print(f'Audio content size in bytes is: {len(response.audio_content)}')
    audio_buffer.write(response.audio_content)

  # Write collected audio outputs to a WAV file.
  with wave.open(synthesis_output_path, 'wb') as wav_file:
    wav_file.setnchannels(1)
    wav_file.setsampwidth(2)
    wav_file.setframerate(24000)
    wav_file.writeframes(audio_buffer.getvalue())
    print(f'Audio content written to file {synthesis_output_path}.')


if __name__ == '__main__':
  client = texttospeech.TextToSpeechClient()
  with open('voice_cloning_key.txt', 'r') as f:
    key = f.read()
  perform_voice_cloning_with_simulated_streaming(
      voice_cloning_key=key,
      simulated_streamed_text=[
          'Hello world!',
          'This is the second text chunk.',
          'This simulates streaming text for synthesis.',
      ],
      language_code='en-US',
      synthesis_output_path='streaming_output.wav',
      tts_client=client,
  )

使用 Chirp 3:HD 語音控制

即時自訂語音支援與 Chirp 3:HD 語音相同的速度控制、暫停控制和自訂發音功能。如要進一步瞭解 Chirp 3:HD 語音控制,請參閱「Chirp 3:HD 語音控制」。

如要為即時自訂語音啟用這三項功能,請以與即時自訂語音相同的方式調整 SynthesizeSpeechRequestStreamingSynthesizeConfig

語音控制功能支援的語言

  • 所有地區皆可使用步調控制功能。

  • 暫停控制項適用於所有語言代碼。

  • 自訂發音功能適用於所有語言代碼,但 bn-INgu-INth-THvi-VN 除外。

啟用多語言轉移功能

即時自訂語音支援特定語言組合的多語言轉移。也就是說,如果使用 en-US 等語言代碼產生語音複製金鑰,該金鑰可用於合成其他語言的語音,例如 es-ES

這個程式碼範例示範如何設定 SynthesizeRequest,使用en-US 語音複製金鑰合成 es-ES

voice_clone_params = texttospeech.VoiceCloneParams(
    voice_cloning_key=en_us_voice_cloning_key
)
request = texttospeech.SynthesizeSpeechRequest(
  input=texttospeech.SynthesisInput(text=transcript),
  voice=texttospeech.VoiceSelectionParams(
      language_code='es-ES', voice_clone=voice_clone_params
  ),
  audio_config=texttospeech.AudioConfig(
      audio_encoding=texttospeech.AudioEncoding.LINEAR16,
      sample_rate_hertz=24000,
  ),
)

設定 StreamingSynthesizeConfig,使用 en-US 語音複製金鑰合成 es-ES 的範例:

voice_clone_params = texttospeech.VoiceCloneParams(
    voice_cloning_key=en_us_voice_cloning_key
)
streaming_config = texttospeech.StreamingSynthesizeConfig(
    voice=texttospeech.VoiceSelectionParams(
        language_code='es-ES', voice_clone=voice_clone_params
    ),
    streaming_audio_config=texttospeech.StreamingAudioConfig(
        audio_encoding=texttospeech.AudioEncoding.PCM,
        sample_rate_hertz=24000,
    ),
)

多語言轉移功能支援的語言

即時自訂語音支援下列語言轉移:

  • 語言代碼為 en-US 的語音複製金鑰可合成下列語言的輸出內容:

    • de-DE
    • es-US
    • es-ES
    • fr-CA
    • fr-FR
    • pt-BR