Chirp 3 的「即時 Custom Voice」功能可讓您使用自己的高品質錄音來訓練模型,打造個人化語音模型。即時 Custom Voice 可快速生成個人語音,並透過 Cloud Text-to-Speech API 使用個人語音來合成音訊,同時支援串流和長篇文字。
技術詳細資料
| 支援的語言 | 查看支援的語言 |
|---|---|
| 區域可用性 | global、us、eu、asia-southeast1、asia-northeast1、europe-west2 |
| 支援的輸出格式 |
|
| 支援的編碼格式 | LINEAR16、PCM、MP3、M4A |
| 支援的功能 |
|
支援的語言
即時 Custom Voice 支援下列語言:
| 語言 | BCP-47 代碼 | 同意聲明 |
|---|---|---|
| 阿拉伯文 (XA) | ar-XA | .أنا مالك هذا الصوت وأوافق على أن تستخدم Google هذا الصوت لإنشاء نموذج صوتي اصطناعي |
| 孟加拉文 (印度) | bn-IN | আমি এই ভয়েসের মালিক এবং আমি একটি সিন্থেটিক ভয়েস মডেল তৈরি করতে এই ভয়েস ব্যবহার করে Google-এর সাথে সম্মতি দিচ্ছি। |
| 中文 (中國) | cmn-CN | 我是此声音的拥有者并授权谷歌使用此声音创建语音合成模型 |
| 英文 (澳洲) | en-AU | I am the owner of this voice and I consent to Google using this voice to create a synthetic voice model. |
| 英文 (印度) | en-IN | I am the owner of this voice and I consent to Google using this voice to create a synthetic voice model. |
| 英文 (英國) | en-GB | I am the owner of this voice and I consent to Google using this voice to create a synthetic voice model. |
| 英文 (美國) | en-US | I am the owner of this voice and I consent to Google using this voice to create a synthetic voice model. |
| 法文 (加拿大) | 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 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 | 나는 이 음성의 소유자이며 구글이 이 음성을 사용하여 음성 합성 모델을 생성할 것을 허용합니다. |
| 馬拉雅拉姆文 (印度) | 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. |
使用即時 Custom Voice
以下各節將探討如何使用 Text-to-Speech API 中的 Chirp 3:即時 Custom Voice 功能。
錄製同意聲明和參考音訊
錄製同意聲明:為遵守即時 Custom Voice 的法律和道德規範,請以適當語言錄製所需的同意聲明,並儲存為單聲道音訊檔案,長度最多 10 秒,且音訊編碼必須符合支援格式 (「I am the owner of this voice, and I consent to Google using this voice to create a synthetic voice model.」(我是這個聲音的擁有者,我同意 Google 用此聲音建立合成語音模型。))
錄製參考音訊:使用電腦麥克風錄製最多 10 秒的音訊,並以支援的音訊編碼格式儲存為單聲道音訊檔案。錄音時應避免背景噪音。請在相同環境中錄製同意聲明和參考音訊。
儲存音訊檔案:將錄好的音訊檔案儲存在指定的 Cloud Storage 位置。
錄製高品質參考音訊和同意聲明音訊的規範
錄製高品質參考音訊和同意聲明音訊時,請遵守下列規範:
- 音訊長度應盡量接近 10 秒。
- 音訊應包含自然停頓和語速。
- 音訊的背景噪音應越少越好。
- 詳情請參閱「支援的音訊編碼」。可使用任何取樣率。
- 模型會重現麥克風的音質,因此如果錄音音質模糊,輸出內容也會模糊。
- 語音應充滿活力,且比最終輸出內容更具表現張力。此外,語音的節奏也應與複製語音的節奏一致。舉例來說,如果參考音訊沒有自然停頓或中斷,複製的語音就不應出現停頓。
- 好的提示詞會比單調無趣的提示詞更興奮有活力,模型會根據這些提示重現這種能量。
使用 REST API 建立即時 Custom Voice
即時 Custom Voice 會以「語音複製金鑰」的形式呈現,這是語音資料的文字字串表示法。
重要注意事項
以下是建立 Custom Voice 時的幾項重要注意事項:
- 語音複製金鑰儲存在用戶端,且應要求提供,因此可建立的語音複製金鑰無數量限制。
- 多個用戶端或裝置可同時使用相同的語音複製金鑰。
- 每個專案每分鐘最多可建立 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,透過即時 Custom Voice 合成語音
使用語音複製金鑰,透過 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 用戶端程式庫,透過即時 Custom Voice 合成語音
本範例使用 Python 用戶端程式庫執行即時 Custom Voice 合成作業,並使用儲存在 voice_cloning_key.txt 檔案的語音複製金鑰。如要生成語音複製金鑰,請參閱「使用 REST API 建立即時 Custom Voice」。
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 用戶端程式庫,透過即時 Custom Voice 進行串流合成
本範例使用 Python 用戶端程式庫執行即時 Custom Voice 串流合成,並使用儲存在 voice_cloning_key.txt 的語音複製金鑰。如要生成語音複製金鑰,請參閱「使用 REST API 建立即時 Custom Voice」。
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 語音相同,即時 Custom Voice 支援語速控制、停頓控制和自訂發音功能。如要進一步瞭解 Chirp 3:HD 語音控制,請參閱「Chirp 3:HD 語音控制」。
如要為即時 Custom Voice 啟用這三項功能,請以設定即時 Custom Voice 相同的方式,來調整 SynthesizeSpeechRequest 或 StreamingSynthesizeConfig。
語音控制支援的語言
語速控制適用於所有語言代碼。
停頓控制適用於所有語言代碼。
自訂發音適用於所有語言代碼,
bn-IN、gu-IN、th-TH和vi-VN除外。
啟用多語言轉移功能
即時 Custom Voice 支援特定語言代碼組合的多語言轉移。也就是說,如果使用 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,
),
)