Crea audio nel formato lungo

Questo documento ti guida nella procedura di sintesi di audio nel formato lungo. La sintesi audio lunga sintetizza in modo asincrono fino a 1 milione di byte in ingresso. Per scoprire di più sui concetti fondamentali di Text-to-Speech, leggi le 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 azioni seguenti. Consulta la pagina Prima di iniziare per maggiori dettagli.

  • Abilita Text-to-Speech in un progetto Google Cloud.
    1. Assicurati che la fatturazione sia abilitata per Text-to-Speech.
    2. Assicurati di disporre dei seguenti ruoli IAM (Identity and Access Management) nel bucket GCS di output.
      • Storage Object Creator
      • Storage Object Viewer
  • Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

    gcloud init

Sintetizza l'audio lungo dal testo tramite la riga di comando

Puoi convertire testo nel formato lungo in audio effettuando una richiesta POST HTTP 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 del file di output GCS nel formato "gs://bucket_name/file_name.wav".

parent: il publisher principale nel formato "projects/{YOUR PROJECT NUMBER}/locations/{YOUR PROJECT LOCATION}".

L'input può contenere fino a 1 MB di caratteri e il limite esatto può variare a seconda dell'input.

  1. Crea un bucket Google Cloud Storage all'interno del progetto che verrà utilizzato per eseguire la sintesi. Assicurati che l'account di servizio utilizzato per eseguire la sintesi disponga dell'accesso in lettura/scrittura al bucket GCS di output.

  2. Esegui la richiesta REST riportata di seguito alla 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.

    Assicurati che l'account di servizio che esegue l'operazione GET abbia il ruolo Editor di Text-to-Speech.

    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 delle seguenti 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 lunga nel campo name. Esegui la richiesta REST riportata di seguito alla riga di comando per eseguire una query sullo stato dell'operazione a lunga esecuzione.

    Assicurati che l'account di servizio che esegue l'operazione GET provenga dallo stesso progetto 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 delle seguenti 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 ed esegui la richiesta REST di seguito.

    Assicurati che l'account di servizio che esegue l'operazione LIST appartenga allo stesso progetto 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 delle seguenti opzioni:

    Dovresti ricevere una risposta JSON simile alla seguente:

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

  5. Una volta completata 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, individua l'errore eseguendo una query con il comando GET REST, correggi l'errore ed invia nuovamente la RPC.

Sintetizza l'audio lungo dal testo utilizzando le librerie client

installa la libreria client

Python

Prima di installare la libreria, assicurati di aver preparato il tuo ambiente per lo sviluppo in Python.

pip install --upgrade google-cloud-texttospeech

Crea dati audio

Puoi usare Text-to-Speech per creare un lungo file audio di voce sintetica umana. Usa il codice seguente per creare un file audio lungo nel bucket GCS.

Python

Prima di eseguire l'esempio, assicurati di aver preparato il tuo ambiente per lo sviluppo in 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, location, output_gcs_uri):
    """
    Synthesizes long input, writing the resulting audio to `output_gcs_uri`.

    Example usage: synthesize_long_audio('12345', 'us-central1', 'gs://{BUCKET_NAME}/{OUTPUT_FILE_NAME}.wav')

    """
    # TODO(developer): Uncomment and set the following variables
    # project_id = 'YOUR_PROJECT_ID'
    # location = 'YOUR_LOCATION'
    # output_gcs_uri = 'YOUR_OUTPUT_GCS_URI'

    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/{location}"

    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 inutili per Google Cloud Platform, utilizza la console Google Cloud per eliminare il progetto se non ti serve.

Passaggi successivi