Creare audio di lunga durata

Questo documento descrive la procedura di sintesi dell'audio in formato lungo. La sintesi audio lunga sintetizza in modo asincrono fino a 1 milione di byte in input. Per scoprire di più sui concetti fondamentali di Text-to-Speech, leggi Nozioni di base di Text-to-Speech.

Prima di iniziare

Prima di poter inviare una richiesta all'API Text-to-Speech, devi aver completato le seguenti azioni. Per informazioni dettagliate, consulta la pagina Prima di iniziare.

Sintetizza audio lunghi dal testo utilizzando la riga di comando

Puoi convertire il testo in formato lungo in audio effettuando una richiesta HTTP POST all'endpoint https://texttospeech.googleapis.com/v1beta1/projects/{$project_number}/locations/global:synthesizeLongAudio. Nel corpo del comando POST, specifica i seguenti campi.

voice: il tipo di voce da sintetizzare.

input.text: il testo da sintetizzare.

audioConfig: il tipo di audio da creare.

output_gcs_uri: il percorso di output Google Cloud nel formato "gs://bucket_name/file_name.wav".

parent: il genitore nel formato "projects/{YOUR_PROJECT_NUMBER}/locations/{YOUR_PROJECT_LOCATION}".

L'input può contenere fino a 1 MB di caratteri. Il limite esatto può variare a seconda dei diversi input.

  1. Crea un bucket di archiviazione Google Cloud nel progetto utilizzato per eseguire la sintesi. Assicurati che il account di servizio utilizzato per eseguire la sintesi abbia accesso in lettura e scrittura al bucket di output Google Cloud .

  2. Esegui la richiesta REST dalla riga di comando per sintetizzare l'audio dal testo utilizzando Text-to-Speech. Il comando utilizza il comando gcloud auth application-default print-access-token per recuperare un token di autorizzazione per la richiesta.

    Metodo HTTP e URL:

    POST https://texttospeech.googleapis.com/v1beta1/projects/12345/locations/global:synthesizeLongAudio

    Corpo JSON della richiesta:

    {
      "parent": "projects/12345/locations/global",
      "audio_config":{
          "audio_encoding":"LINEAR16"
      },
      "input":{
          "text":"hello"
      },
      "voice":{
          "language_code":"en-us",
          "name":"en-us-Standard-A"
      },
      "output_gcs_uri": "gs://bucket_name/file_name.wav"
    }
    

    Per inviare la richiesta, espandi una di queste opzioni:

    Dovresti ricevere una risposta JSON simile alla seguente:

    {
      "name": "23456",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.texttospeech.v1beta1.SynthesizeLongAudioMetadata",
        "progressPercentage": 0,
        "startTime": "2022-12-20T00:46:56.296191037Z",
        "lastUpdateTime": "2022-12-20T00:46:56.296191037Z"
      },
      "done": false
    }
    

  3. L'output JSON per il comando REST contiene il nome dell'operazione di lunga durata nel campo name. Esegui la richiesta REST dalla riga di comando per eseguire query sullo stato delloperazione a lunga esecuzione.

    Assicurati che il account di servizio che esegue l'operazione GET provenga dallo stesso progetto di quello utilizzato per la sintesi.

    Metodo HTTP e URL:

    GET https://texttospeech.googleapis.com/v1beta1/projects/12345/locations/global/operations/23456

    Per inviare la richiesta, espandi una di queste opzioni:

    Dovresti ricevere una risposta JSON simile alla seguente:

    {
      "name": "projects/12345/locations/global/operations/23456",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.texttospeech.v1beta1.SynthesizeLongAudioMetadata",
        "progressPercentage": 100
      },
      "done": true
    }
    

  4. Esegui una query sull'elenco di tutte le operazioni in esecuzione in un determinato progetto, esegui la richiesta REST.

    Assicurati che il account di servizio che esegue l'operazione LIST provenga dallo stesso progetto di quello utilizzato per la sintesi.

    Metodo HTTP e URL:

    GET https://texttospeech.googleapis.com/v1beta1/projects/12345/locations/global/operations

    Per inviare la richiesta, espandi una di queste opzioni:

    Dovresti ricevere una risposta JSON simile alla seguente:

    {
      "operations": [
        {
          "name": "12345",
          "done": false
        },
        {
          "name": "23456",
          "done": false
        }
      ],
      "nextPageToken": ""
    }
    

  5. Una volta completata correttamente l'operazione a lunga esecuzione, trova il file audio di output nell'URI del bucket specificato nel campo output_gcs_uri. Se l'operazione non è stata completata correttamente, individua l'errore eseguendo una query utilizzando il comando GET REST, correggi l'errore ed esegui di nuovo la RPC.

Sintetizzare audio lunghi dal testo utilizzando le librerie client

Segui queste istruzioni per sintetizzare audio lunghi.

installa la libreria client

Python

Prima di installare la libreria, assicurati di aver preparato l'ambiente per lo sviluppo Python.

pip install --upgrade google-cloud-texttospeech

Creare dati audio

Puoi utilizzare Text-to-Speech per creare un lungo file audio di sintesi vocale umana. Utilizza il seguente codice per creare un file audio lungo nel bucket Google Cloud .

Python

Prima di eseguire l'esempio, assicurati di aver preparato l'ambiente per lo sviluppo Python.

# Copyright 2023 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.

from google.cloud import texttospeech


def synthesize_long_audio(project_id: str, output_gcs_uri: str) -> None:
    """
    Synthesizes long input, writing the resulting audio to `output_gcs_uri`.

    Args:
        project_id: ID or number of the Google Cloud project you want to use.
        output_gcs_uri: Specifies a Cloud Storage URI for the synthesis results.
            Must be specified in the format:
            ``gs://bucket_name/object_name``, and the bucket must
            already exist.
    """

    client = texttospeech.TextToSpeechLongAudioSynthesizeClient()

    input = texttospeech.SynthesisInput(
        text="Test input. Replace this with any text you want to synthesize, up to 1 million bytes long!"
    )

    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.LINEAR16
    )

    voice = texttospeech.VoiceSelectionParams(
        language_code="en-US", name="en-US-Standard-A"
    )

    parent = f"projects/{project_id}/locations/us-central1"

    request = texttospeech.SynthesizeLongAudioRequest(
        parent=parent,
        input=input,
        audio_config=audio_config,
        voice=voice,
        output_gcs_uri=output_gcs_uri,
    )

    operation = client.synthesize_long_audio(request=request)
    # Set a deadline for your LRO to finish. 300 seconds is reasonable, but can be adjusted depending on the length of the input.
    # If the operation times out, that likely means there was an error. In that case, inspect the error, and try again.
    result = operation.result(timeout=300)
    print(
        "\nFinished processing, check your GCS bucket to find your audio file! Printing what should be an empty result: ",
        result,
    )

Esegui la pulizia

Per evitare addebiti non necessari di Google Cloud , utilizzaGoogle Cloud console per eliminare il progetto se non ti serve.

Passaggi successivi