המרת טקסט לדיבור באמצעות סטרימינג דו-כיווני

במאמר הזה נסביר איך להמיר טקסט לאודיו באמצעות סטרימינג דו-כיווני.

סטרימינג דו-כיווני מאפשר לשלוח קלט טקסט ולקבל נתוני אודיו בו-זמנית. כלומר, אתם יכולים להתחיל לסנתז דיבור לפני שכל טקסט הקלט נשלח, וכך לצמצם את זמן האחזור ולאפשר אינטראקציות בזמן אמת. עוזרים קוליים ומשחקים אינטראקטיביים משתמשים בסטרימינג דו-כיווני כדי ליצור אפליקציות דינמיות ורספונסיביות יותר.

למידע נוסף על מושגי היסוד של Cloud Text-to-Speech, קראו את המאמר היסודות של Cloud Text-to-Speech.

לפני שמתחילים

כדי לשלוח בקשה ל-Cloud Text-to-Speech API, צריך לבצע את הפעולות הבאות.

  1. התקינו את ה-CLI של Google Cloud.

  2. הגדירו שה-CLI של gcloud ישתמש בזהות המאוחדת שלכם.

    איך נכנסים ל-CLI של gcloud באמצעות הזהות המאוחדת?

  3. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  4. יוצרים או בוחרים פרויקט ב- Google Cloud .

    התפקידים שנדרשים כדי לבחור או ליצור פרויקט

    • בחירת פרויקט: כדי לבחור פרויקט לא נדרש תפקיד IAM ספציפי – אתם יכולים לבחור כל פרויקט שקיבלתם בו תפקיד.
    • יצירת פרויקט: כדי ליצור פרויקט, צריך את התפקיד "יצירת פרויקטים" (roles/resourcemanager.projectCreator), שכולל את ההרשאה resourcemanager.projects.create. איך מקצים תפקידים?
    • יוצרים פרויקט ב- Google Cloud :

      gcloud projects create PROJECT_ID

      מחליפים את PROJECT_ID בשם של הפרויקט ב- Google Cloud שאתם יוצרים.

    • בוחרים את הפרויקט שיצרתם ב- Google Cloud :

      gcloud config set project PROJECT_ID

      מחליפים את PROJECT_ID בשם הפרויקט ב- Google Cloud .

  5. מוודאים שהחיוב מופעל בפרויקט ב- Google Cloud .

  6. מפעילים את Cloud Text-to-Speech API, אם הוא עדיין לא מופעל:

    התפקידים שנדרשים כדי להפעיל ממשקי API

    כדי להפעיל ממשקי API, צריך את ההרשאה serviceusage.services.enable. אם יצרתם את הפרויקט, סביר להניח שכבר יש לכם את ההרשאה הזו דרך התפקיד "בעלים" (roles/owner). אחרת, תוכלו לקבל את ההרשאה הזו דרך התפקיד "אדמין בממשק 'שימוש בשירות'" (roles/serviceusage.serviceUsageAdmin). כך מקצים תפקידים.

    gcloud services enable texttospeech.googleapis.com

המרת טקסט לדיבור באמצעות סטרימינג דו-כיווני

התקנת ספריית הלקוח

Python

לפני שמתקינים את הספרייה, צריך לוודא שהסביבה מוכנה לפיתוח ב-Python.

pip install --upgrade google-cloud-texttospeech

שליחת רצף של טקסט וקבלת רצף של אודיו

ה-API מקבל זרם של בקשות מסוג StreamingSynthesizeRequest, שמכילות StreamingSynthesisInput או StreamingSynthesizeConfig.

לפני ששולחים בקשת StreamingSynthesizeRequest עם StreamingSynthesisInput שמספקת קלט טקסט, צריך לשלוח בדיוק בקשת StreamingSynthesizeRequest אחת עם StreamingSynthesizeConfig.

אפשר להשתמש בסטרימינג של Cloud Text-to-Speech רק עם Chirp 3: HD voices.

Python

לפני שמריצים את הדוגמה, חשוב לוודא שהכנתם את הסביבה לפיתוח ב-Python.

#!/usr/bin/env python
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""Google Cloud Text-To-Speech API streaming sample application .

Example usage:
    python streaming_tts_quickstart.py
"""


def run_streaming_tts_quickstart():
    """Synthesizes speech from a stream of input text."""
    from google.cloud import texttospeech

    client = texttospeech.TextToSpeechClient()

    # See https://cloud.google.com/text-to-speech/docs/voices for all voices.
    streaming_config = texttospeech.StreamingSynthesizeConfig(
        voice=texttospeech.VoiceSelectionParams(
            name="en-US-Chirp3-HD-Charon",
            language_code="en-US",
        )
    )

    # Set the config for your stream. The first request must contain your config, and then each subsequent request must contain text.
    config_request = texttospeech.StreamingSynthesizeRequest(
        streaming_config=streaming_config
    )

    text_iterator = [
        "Hello there. ",
        "How are you ",
        "today? It's ",
        "such nice weather outside.",
    ]

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

    streaming_responses = client.streaming_synthesize(request_generator())

    for response in streaming_responses:
        print(f"Audio content size in bytes is: {len(response.audio_content)}")


if __name__ == "__main__":
    run_streaming_tts_quickstart()

הסרת המשאבים

כדי להימנע מחיובים מיותרים ב-Google Cloud Platform, אם אתם לא צריכים את הפרויקט, אתם יכולים למחוק אותו באמצעותGoogle Cloud console .

המאמרים הבאים