תמלול של קובצי אודיו קצרים

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

זיהוי דיבור סינכרוני מחזיר את הטקסט שזוהה עבור אודיו קצר (פחות מ-60 שניות). כדי לעבד בקשה לזיהוי דיבור של אודיו שאורכו יותר מ-60 שניות, צריך להשתמש ב-Asynchronous Speech Recognition.

אפשר לשלוח תוכן אודיו ישירות אל Cloud Speech-to-Text מקובץ מקומי, או ש-Cloud Speech-to-Text יכול לעבד תוכן אודיו שמאוחסן בקטגוריה של Cloud Storage. בדף המכסות והמגבלות מפורטות המגבלות על בקשות סינכרוניות לזיהוי דיבור.

ביצוע זיהוי דיבור סינכרוני בקובץ מקומי

הדוגמה הבאה מציגה ביצוע של זיהוי דיבור סינכרוני בקובץ אודיו מקומי:

REST

פרטים נוספים זמינים בנקודת קצה ל-API של speech:recognize. מידע נוסף על הגדרת גוף הבקשה מופיע במאמרי העזרה בנושא RecognitionConfig.

תוכן האודיו שמועבר בגוף הבקשה חייב להיות בקידוד Base64. כאן אפשר לקרוא מידע נוסף על קידוד base64 של אודיו. מידע נוסף על השדה content מופיע במאמר RecognitionAudio.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LANGUAGE_CODE: קוד BCP-47 של השפה שמדוברת בקטע האודיו.
  • ENCODING: הקידוד של האודיו שרוצים לתמלל.
  • SAMPLE_RATE_HERTZ: קצב הדגימה בהרץ של האודיו שרוצים לתמלל.
  • ENABLE_WORD_TIME_OFFSETS: מפעילים את השדה הזה אם רוצים לקבל את ההיסטים (חותמות הזמן) של תחילת המילה וסוף המילה.
  • INPUT_AUDIO: מחרוזת בקידוד base64 של נתוני האודיו שרוצים לתמלל.
  • PROJECT_ID: המזהה האלפאנומרי של הפרויקט ב- Google Cloud .

ה-method של ה-HTTP וכתובת ה-URL:

POST https://speech.googleapis.com/v2/speech:recognize

תוכן בקשת JSON:

{
  "config": {
      "languageCode": "LANGUAGE_CODE",
      "encoding": "ENCODING",
      "sampleRateHertz": SAMPLE_RATE_HERTZ,
      "enableWordTimeOffsets": ENABLE_WORD_TIME_OFFSETS
  },
  "audio": {
    "content": "INPUT_AUDIO"
  }
}

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.98267895
        }
      ]
    }
  ]
}

gcloud

פרטים נוספים זמינים בפקודה recognize.

כדי לבצע זיהוי דיבור בקובץ מקומי, משתמשים ב-Google Cloud CLI ומעבירים את הנתיב של הקובץ המקומי שרוצים לבצע בו זיהוי דיבור.

gcloud ml speech recognize PATH-TO-LOCAL-FILE --language-code='en-US'

אם הבקשה מצליחה, השרת מחזיר תגובה בפורמט JSON:

{
  "results": [
    {
      "alternatives": [
        {
          "confidence": 0.9840146,
          "transcript": "how old is the Brooklyn Bridge"
        }
      ]
    }
  ]
}

Go

מידע על התקנה ושימוש בספריית הלקוח של Cloud STT מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Go API.

כדי לבצע אימות ב-Cloud STT, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


func recognize(w io.Writer, file string) error {
	ctx := context.Background()

	client, err := speech.NewClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	data, err := os.ReadFile(file)
	if err != nil {
		return err
	}

	// Send the contents of the audio file with the encoding and
	// and sample rate information to be transcripted.
	resp, err := client.Recognize(ctx, &speechpb.RecognizeRequest{
		Config: &speechpb.RecognitionConfig{
			Encoding:        speechpb.RecognitionConfig_LINEAR16,
			SampleRateHertz: 16000,
			LanguageCode:    "en-US",
		},
		Audio: &speechpb.RecognitionAudio{
			AudioSource: &speechpb.RecognitionAudio_Content{Content: data},
		},
	})

	// Print the results.
	for _, result := range resp.Results {
		for _, alt := range result.Alternatives {
			fmt.Fprintf(w, "\"%v\" (confidence=%3f)\n", alt.Transcript, alt.Confidence)
		}
	}
	return nil
}

Java

מידע על התקנה ושימוש בספריית הלקוח של Cloud STT מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Java API.

כדי לבצע אימות ב-Cloud STT, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * Performs speech recognition on raw PCM audio and prints the transcription.
 *
 * @param fileName the path to a PCM audio file to transcribe.
 */
public static void syncRecognizeFile(String fileName) throws Exception {
  try (SpeechClient speech = SpeechClient.create()) {
    Path path = Paths.get(fileName);
    byte[] data = Files.readAllBytes(path);
    ByteString audioBytes = ByteString.copyFrom(data);

    // Configure request with local raw PCM audio
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .build();
    RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();

    // Use blocking call to get audio transcript
    RecognizeResponse response = speech.recognize(config, audio);
    List<SpeechRecognitionResult> results = response.getResultsList();

    for (SpeechRecognitionResult result : results) {
      // There can be several alternative transcripts for a given chunk of speech. Just use the
      // first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
      System.out.printf("Transcription: %s%n", alternative.getTranscript());
    }
  }
}

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Cloud STT מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Node.js API.

כדי לבצע אימות ב-Cloud STT, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const fs = require('fs');
const speech = require('@google-cloud/speech');

// Creates a client
const client = new speech.SpeechClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const filename = 'Local path to audio file, e.g. /path/to/audio.raw';
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code, e.g. en-US';

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
};
const audio = {
  content: fs.readFileSync(filename).toString('base64'),
};

const request = {
  config: config,
  audio: audio,
};

// Detects speech in the audio file
const [response] = await client.recognize(request);
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log('Transcription: ', transcription);

Python

מידע על התקנה ושימוש בספריית הלקוח של Cloud STT מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Python API.

כדי לבצע אימות ב-Cloud STT, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import speech


def transcribe_file(audio_file: str) -> speech.RecognizeResponse:
    """Transcribe the given audio file.
    Args:
        audio_file (str): Path to the local audio file to be transcribed.
            Example: "resources/audio.wav"
    Returns:
        cloud_speech.RecognizeResponse: The response containing the transcription results
    """
    client = speech.SpeechClient()

    with open(audio_file, "rb") as f:
        audio_content = f.read()

    audio = speech.RecognitionAudio(content=audio_content)
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code="en-US",
    )

    response = client.recognize(config=config, audio=audio)

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

שפות נוספות

C#‎: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה של Cloud STT ל-‎ .NET.

PHP: צריך לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה של Cloud STT ל-PHP.

Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף של ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Cloud STT ל-Ruby.

ביצוע זיהוי דיבור סינכרוני בקובץ מרוחק

לנוחיותכם, Cloud Speech-to-Text API יכול לבצע זיהוי דיבור סינכרוני ישירות בקובץ אודיו שנמצא ב-Cloud Storage, בלי שתצטרכו לשלוח את התוכן של קובץ האודיו בגוף הבקשה.

דוגמה לביצוע זיהוי דיבור סינכרוני בקובץ שנמצא ב-Cloud Storage:

REST

פרטים נוספים זמינים בנקודת קצה ל-API של speech:recognize. מידע נוסף על הגדרת גוף הבקשה מופיע במאמרי העזרה בנושא RecognitionConfig.

תוכן האודיו שמועבר בגוף הבקשה חייב להיות בקידוד Base64. כאן אפשר לקרוא מידע נוסף על קידוד base64 של אודיו. מידע נוסף על השדה content מופיע במאמר RecognitionAudio.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LANGUAGE_CODE: קוד BCP-47 של השפה שמדוברת בקטע האודיו.
  • ENCODING: הקידוד של האודיו שרוצים לתמלל.
  • SAMPLE_RATE_HERTZ: קצב הדגימה בהרץ של האודיו שרוצים לתמלל.
  • ENABLE_WORD_TIME_OFFSETS: מפעילים את השדה הזה אם רוצים לקבל את ההיסטים (חותמות הזמן) של תחילת המילה וסוף המילה.
  • STORAGE_BUCKET: קטגוריה של Cloud Storage.
  • INPUT_AUDIO: קובץ נתוני האודיו שרוצים לתמלל.
  • PROJECT_ID: המזהה האלפאנומרי של הפרויקט ב- Google Cloud .

ה-method של ה-HTTP וכתובת ה-URL:

POST https://speech.googleapis.com/v2/speech:recognize

תוכן בקשת JSON:

{
  "config": {
      "languageCode": "LANGUAGE_CODE",
      "encoding": "ENCODING",
      "sampleRateHertz": SAMPLE_RATE_HERTZ,
      "enableWordTimeOffsets": ENABLE_WORD_TIME_OFFSETS
  },
  "audio": {
    "uri": "gs://STORAGE_BUCKET/INPUT_AUDIO"
  }
}

כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.98267895
        }
      ]
    }
  ]
}

gcloud

פרטים נוספים זמינים בפקודה recognize.

כדי לבצע זיהוי דיבור בקובץ מקומי, משתמשים ב-Google Cloud CLI ומעבירים את הנתיב של הקובץ המקומי שרוצים לבצע בו זיהוי דיבור.

gcloud ml speech recognize 'gs://cloud-samples-tests/speech/brooklyn.flac' \
--language-code='en-US'

אם הבקשה מצליחה, השרת מחזיר תגובה בפורמט JSON:

{
  "results": [
    {
      "alternatives": [
        {
          "confidence": 0.9840146,
          "transcript": "how old is the Brooklyn Bridge"
        }
      ]
    }
  ]
}

Go

מידע על התקנה ושימוש בספריית הלקוח של Cloud STT מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Go API.

כדי לבצע אימות ב-Cloud STT, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


func recognizeGCS(w io.Writer, gcsURI string) error {
	ctx := context.Background()

	client, err := speech.NewClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	// Send the request with the URI (gs://...)
	// and sample rate information to be transcripted.
	resp, err := client.Recognize(ctx, &speechpb.RecognizeRequest{
		Config: &speechpb.RecognitionConfig{
			Encoding:        speechpb.RecognitionConfig_LINEAR16,
			SampleRateHertz: 16000,
			LanguageCode:    "en-US",
		},
		Audio: &speechpb.RecognitionAudio{
			AudioSource: &speechpb.RecognitionAudio_Uri{Uri: gcsURI},
		},
	})

	// Print the results.
	for _, result := range resp.Results {
		for _, alt := range result.Alternatives {
			fmt.Fprintf(w, "\"%v\" (confidence=%3f)\n", alt.Transcript, alt.Confidence)
		}
	}
	return nil
}

Java

מידע על התקנה ושימוש בספריית הלקוח של Cloud STT מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Java API.

כדי לבצע אימות ב-Cloud STT, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

/**
 * Performs speech recognition on remote FLAC file and prints the transcription.
 *
 * @param gcsUri the path to the remote FLAC audio file to transcribe.
 */
public static void syncRecognizeGcs(String gcsUri) throws Exception {
  // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
  try (SpeechClient speech = SpeechClient.create()) {
    // Builds the request for remote FLAC file
    RecognitionConfig config =
        RecognitionConfig.newBuilder()
            .setEncoding(AudioEncoding.FLAC)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .build();
    RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();

    // Use blocking call for getting audio transcript
    RecognizeResponse response = speech.recognize(config, audio);
    List<SpeechRecognitionResult> results = response.getResultsList();

    for (SpeechRecognitionResult result : results) {
      // There can be several alternative transcripts for a given chunk of speech. Just use the
      // first (most likely) one here.
      SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
      System.out.printf("Transcription: %s%n", alternative.getTranscript());
    }
  }
}

Node.js

מידע על התקנה ושימוש בספריית הלקוח של Cloud STT מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Node.js API.

כדי לבצע אימות ב-Cloud STT, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech');

// Creates a client
const client = new speech.SpeechClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const gcsUri = 'gs://my-bucket/audio.raw';
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code, e.g. en-US';

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
};
const audio = {
  uri: gcsUri,
};

const request = {
  config: config,
  audio: audio,
};

// Detects speech in the audio file
const [response] = await client.recognize(request);
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log('Transcription: ', transcription);

Python

מידע על התקנה ושימוש בספריית הלקוח של Cloud STT מופיע במאמר ספריות הלקוח של Cloud STT. מידע נוסף מופיע במאמרי העזרה של Cloud STT Python API.

כדי לבצע אימות ב-Cloud STT, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

def transcribe_gcs(audio_uri: str) -> speech.RecognizeResponse:
    """Transcribes the audio file specified by the gcs_uri.
    Args:
        audio_uri (str): The Google Cloud Storage URI of the input audio file.
            E.g., gs://cloud-samples-data/speech/audio.flac
    Returns:
        cloud_speech.RecognizeResponse: The response containing the transcription results
    """
    from google.cloud import speech

    client = speech.SpeechClient()

    audio = speech.RecognitionAudio(uri=audio_uri)
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.FLAC,
        sample_rate_hertz=16000,
        language_code="en-US",
    )

    response = client.recognize(config=config, audio=audio)

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(f"Transcript: {result.alternatives[0].transcript}")

    return response

שפות נוספות

C#‎: צריך לפעול לפי הוראות ההגדרה של C# ‎ בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה של Cloud STT ל-‎ .NET.

PHP: צריך לפעול לפי הוראות ההגדרה של PHP בדף של ספריות הלקוח ואז לעבור אל מאמרי העזרה של Cloud STT ל-PHP.

Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף של ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Cloud STT ל-Ruby.