Performing Streaming Speech Recognition

Streaming Speech Recognition allows you to stream audio to the Cloud Speech API and receive a stream speech recognition results in real time as the audio is processed. See also the audio limits for streaming speech recognition requests. Streaming speech recognition is available via gRPC only.

This section demonstrates a few ways to perform streaming speech recognition on audio.

The Cloud Speech API v1 is officially released and is generally available from the https://speech.googleapis.com/v1/speech endpoint. The Client Libraries are released as Alpha and will likely be changed in backward-incompatible ways. The client libraries are currently not recommended for production use.

These samples require that you have set up gcloud and have created and activated a service account. For information about setting up gcloud, and also creating and activating a service account, see Quickstart.

Performing Streaming Speech Recognition on a Local File

Here is an example of performing streaming speech recognition on a local audio file:

C#

For more on installing and creating a Cloud Speech API client, refer to Cloud Speech API Client Libraries.

static async Task<object> StreamingRecognizeAsync(string filePath)
{
    var speech = SpeechClient.Create();
    var streamingCall = speech.StreamingRecognize();
    // Write the initial request with the config.
    await streamingCall.WriteAsync(
        new StreamingRecognizeRequest()
        {
            StreamingConfig = new StreamingRecognitionConfig()
            {
                Config = new RecognitionConfig()
                {
                    Encoding =
                    RecognitionConfig.Types.AudioEncoding.Linear16,
                    SampleRateHertz = 16000,
                    LanguageCode = "en",
                },
                InterimResults = true,
            }
        });
    // Print responses as they arrive.
    Task printResponses = Task.Run(async () =>
    {
        while (await streamingCall.ResponseStream.MoveNext(
            default(CancellationToken)))
        {
            foreach (var result in streamingCall.ResponseStream
                .Current.Results)
            {
                foreach (var alternative in result.Alternatives)
                {
                    Console.WriteLine(alternative.Transcript);
                }
            }
        }
    });
    // Stream the file content to the API.  Write 2 32kb chunks per 
    // second.
    using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
    {
        var buffer = new byte[32 * 1024];
        int bytesRead;
        while ((bytesRead = await fileStream.ReadAsync(
            buffer, 0, buffer.Length)) > 0)
        {
            await streamingCall.WriteAsync(
                new StreamingRecognizeRequest()
                {
                    AudioContent = Google.Protobuf.ByteString
                    .CopyFrom(buffer, 0, bytesRead),
                });
            await Task.Delay(500);
        };
    }
    await streamingCall.WriteCompleteAsync();
    await printResponses;
    return 0;
}

Java

For more on installing and creating a Cloud Speech API client, refer to Cloud Speech API Client Libraries.

public static void streamingRecognizeFile(String fileName) throws Exception, IOException {
  Path path = Paths.get(fileName);
  byte[] data = Files.readAllBytes(path);

  // Instantiates a client with GOOGLE_APPLICATION_CREDENTIALS
  SpeechClient speech = SpeechClient.create();

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

  class ResponseApiStreamingObserver<T> implements ApiStreamObserver<T> {
    private final SettableFuture<List<T>> future = SettableFuture.create();
    private final List<T> messages = new java.util.ArrayList<T>();

    @Override
    public void onNext(T message) {
      messages.add(message);
    }

    @Override
    public void onError(Throwable t) {
      future.setException(t);
    }

    @Override
    public void onCompleted() {
      future.set(messages);
    }

    // Returns the SettableFuture object to get received messages / exceptions.
    public SettableFuture<List<T>> future() {
      return future;
    }
  }

  ResponseApiStreamingObserver<StreamingRecognizeResponse> responseObserver =
      new ResponseApiStreamingObserver<StreamingRecognizeResponse>();

  StreamingCallable<StreamingRecognizeRequest,StreamingRecognizeResponse> callable =
      speech.streamingRecognizeCallable();

  ApiStreamObserver<StreamingRecognizeRequest> requestObserver =
      callable.bidiStreamingCall(responseObserver);

  // The first request must **only** contain the audio configuration:
  requestObserver.onNext(StreamingRecognizeRequest.newBuilder()
      .setStreamingConfig(config)
      .build());

  // Subsequent requests must **only** contain the audio data.
  requestObserver.onNext(StreamingRecognizeRequest.newBuilder()
      .setAudioContent(ByteString.copyFrom(data))
      .build());

  // Mark transmission as completed after sending the data.
  requestObserver.onCompleted();

  List<StreamingRecognizeResponse> responses = responseObserver.future().get();

  for (StreamingRecognizeResponse response: responses) {
    // For streaming recognize, the results list has one is_final result (if available) followed
    // by a number of in-progress results (if iterim_results is true) for subsequent utterances.
    // Just print the first result here.
    StreamingRecognitionResult result = response.getResultsList().get(0);
    // 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.println(alternative.getTranscript());
  }
  speech.close();
}

Node.js

For more on installing and creating a Cloud Speech API client, refer to Cloud Speech API Client Libraries.

const fs = require('fs');

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

// Instantiates a client
const speech = Speech();

// The path to the local file on which to perform speech recognition, e.g. /path/to/audio.raw
// const filename = '/path/to/audio.raw';

// The encoding of the audio file, e.g. 'LINEAR16'
// const encoding = 'LINEAR16';

// The sample rate of the audio file in hertz, e.g. 16000
// const sampleRateHertz = 16000;

// The BCP-47 language code to use, e.g. 'en-US'
// const languageCode = 'en-US';

const request = {
  config: {
    encoding: encoding,
    sampleRateHertz: sampleRateHertz,
    languageCode: languageCode
  },
  interimResults: false // If you want interim results, set this to true
};

// Stream the audio to the Google Cloud Speech API
const recognizeStream = speech.streamingRecognize(request)
  .on('error', console.error)
  .on('data', (data) => {
    console.log(
        `Transcription: ${data.results[0].alternatives[0].transcript}`);
  });

// Stream an audio file from disk to the Speech API, e.g. "./resources/audio.raw"
fs.createReadStream(filename).pipe(recognizeStream);

PHP

For more on installing and creating a Cloud Speech API client, refer to Cloud Speech API Client Libraries.

use Google\Cloud\Speech\V1\SpeechClient;
use Google\Cloud\Speech\V1\RecognitionConfig;
use Google\Cloud\Speech\V1\StreamingRecognitionConfig;
use Google\Cloud\Speech\V1\StreamingRecognizeRequest;
use Google\Cloud\Speech\V1\RecognitionConfig_AudioEncoding;

/**
 * Transcribe an audio file using Google Cloud Speech API
 * Example:
 * ```
 * $audoEncoding =  Google\Cloud\Speech\V1\RecognitionConfig_AudioEncoding::WAV
 * streaming_recognize('/path/to/audiofile.wav', 'en-US');
 * ```.
 *
 * @param string $audioFile path to an audio file.
 * @param string $languageCode The language of the content to
 *     be recognized. Accepts BCP-47 (e.g., `"en-US"`, `"es-ES"`).
 * @param string $encoding
 * @param string $sampleRateHertz
 *
 * @return string the text transcription
 */
function streaming_recognize($audioFile, $languageCode, $encoding, $sampleRateHertz)
{
    if (!defined('Grpc\STATUS_OK')) {
        throw new \Exception('Install the grpc extension ' .
            '(pecl install grpc)');
    }
    if (!class_exists('Google\Cloud\Speech\V1\SpeechGrpcClient')) {
        throw new \Exception('Install the proto client PHP library ' .
            '(composer require google/proto-client)');
    }
    if (!class_exists('Google\GAX\GrpcConstants')) {
        throw new \Exception('Install the GAX library ' .
            '(composer require google/gax)');
    }

    $speechClient = new SpeechClient();
    try {
        $config = new RecognitionConfig();
        $config->setLanguageCode($languageCode);
        $config->setSampleRateHertz($sampleRateHertz);
        // encoding must be an enum, convert from string
        $encodingEnum = constant(RecognitionConfig_AudioEncoding::class . '::' . $encoding);
        $config->setEncoding($encodingEnum);

        $strmConfig = new StreamingRecognitionConfig();
        $strmConfig->setConfig($config);

        $strmReq = new StreamingRecognizeRequest();
        $strmReq->setStreamingConfig($strmConfig);

        $strm = $speechClient->streamingRecognize();
        $strm->write($strmReq);

        $strmReq = new StreamingRecognizeRequest();
        $f = fopen($audioFile, "rb");
        $fsize = filesize($audioFile);
        $bytes = fread($f, $fsize);
        $strmReq->setAudioContent($bytes);
        $strm->write($strmReq);

        foreach ($strm->closeWriteAndReadAll() as $response) {
            foreach ($response->getResults() as $result) {
                foreach ($result->getAlternatives() as $alt) {
                    printf("Transcription: %s\n", $alt->getTranscript());
                }
            }
        }
    } finally {
        $speechClient->close();
    }
}

Python

For more on installing and creating a Cloud Speech API client, refer to Cloud Speech API Client Libraries.

def transcribe_streaming(stream_file):
    """Streams transcription of the given audio file."""
    from google.cloud import speech
    from google.cloud.speech import enums
    from google.cloud.speech import types
    client = speech.SpeechClient()

    with io.open(stream_file, 'rb') as audio_file:
        content = audio_file.read()

    # In practice, stream should be a generator yielding chunks of audio data.
    stream = [content]
    requests = (types.StreamingRecognizeRequest(audio_content=chunk)
                for chunk in stream)

    config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code='en-US')
    streaming_config = types.StreamingRecognitionConfig(config=config)

    # streaming_recognize returns a generator.
    responses = client.streaming_recognize(streaming_config, requests)

    for response in responses:
        for result in response.results:
            print('Finished: {}'.format(result.is_final))
            print('Stability: {}'.format(result.stability))
            alternatives = result.alternatives
            for alternative in alternatives:
                print('Confidence: {}'.format(alternative.confidence))
                print('Transcript: {}'.format(alternative.transcript))

Ruby

For more on installing and creating a Cloud Speech API client, refer to Cloud Speech API Client Libraries.

# project_id      = "Your Google Cloud project ID"
# audio_file_path = "Path to file on which to perform speech recognition"

require "google/cloud/speech"

speech = Google::Cloud::Speech.new project: project_id
stream = speech.stream encoding:    :linear16,
                       sample_rate: 16000,
                       language:    "en-US"

audio_content = File.binread audio_file_path
bytes_total   = audio_content.size
bytes_sent    = 0
chunk_size    = 32000

# Send chunks of the audio content to the Speech API 1 second at a time
while bytes_sent < bytes_total do
  stream.send audio_content[bytes_sent, chunk_size]
  bytes_sent += chunk_size
  sleep 1
end

# Signal the completion of audio content
stream.stop

stream.wait_until_complete!

results = stream.results

results.each do |result|
  puts "Transcript: #{result.transcript}"
end

While you can stream a local audio file to the Cloud Speech API, it is recommended that you perform synchronous or asynchronous audio recognition for batch mode results.

Performing Streaming Speech Recognition on an Audio Stream

The more interesting streaming use case is streaming real-time audio to the Cloud Speech API.

Here is an example of performing streaming speech recognition on an audio stream received from a microphone:

C#

For more on installing and creating a Cloud Speech API client, refer to Cloud Speech API Client Libraries.

static async Task<object> StreamingMicRecognizeAsync(int seconds)
{
    if (NAudio.Wave.WaveIn.DeviceCount < 1)
    {
        Console.WriteLine("No microphone!");
        return -1;
    }
    var speech = SpeechClient.Create();
    var streamingCall = speech.StreamingRecognize();
    // Write the initial request with the config.
    await streamingCall.WriteAsync(
        new StreamingRecognizeRequest()
        {
            StreamingConfig = new StreamingRecognitionConfig()
            {
                Config = new RecognitionConfig()
                {
                    Encoding =
                    RecognitionConfig.Types.AudioEncoding.Linear16,
                    SampleRateHertz = 16000,
                    LanguageCode = "en",
                },
                InterimResults = true,
            }
        });
    // Print responses as they arrive.
    Task printResponses = Task.Run(async () =>
    {
        while (await streamingCall.ResponseStream.MoveNext(
            default(CancellationToken)))
        {
            foreach (var result in streamingCall.ResponseStream
                .Current.Results)
            {
                foreach (var alternative in result.Alternatives)
                {
                    Console.WriteLine(alternative.Transcript);
                }
            }
        }
    });
    // Read from the microphone and stream to API.
    object writeLock = new object();
    bool writeMore = true;
    var waveIn = new NAudio.Wave.WaveInEvent();
    waveIn.DeviceNumber = 0;
    waveIn.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
    waveIn.DataAvailable +=
        (object sender, NAudio.Wave.WaveInEventArgs args) =>
        {
            lock (writeLock)
            {
                if (!writeMore) return;
                streamingCall.WriteAsync(
                    new StreamingRecognizeRequest()
                    {
                        AudioContent = Google.Protobuf.ByteString
                            .CopyFrom(args.Buffer, 0, args.BytesRecorded)
                    }).Wait();
            }
        };
    waveIn.StartRecording();
    Console.WriteLine("Speak now.");
    await Task.Delay(TimeSpan.FromSeconds(seconds));
    // Stop recording and shut down.
    waveIn.StopRecording();
    lock (writeLock) writeMore = false;
    await streamingCall.WriteCompleteAsync();
    await printResponses;
    return 0;
}

Go

For more on installing and creating a Cloud Speech API client, refer to Cloud Speech API Client Libraries.

client, err := speech.NewClient(ctx)
if err != nil {
	log.Fatal(err)
}
stream, err := client.StreamingRecognize(ctx)
if err != nil {
	log.Fatal(err)
}
// Send the initial configuration message.
if err := stream.Send(&speechpb.StreamingRecognizeRequest{
	StreamingRequest: &speechpb.StreamingRecognizeRequest_StreamingConfig{
		StreamingConfig: &speechpb.StreamingRecognitionConfig{
			Config: &speechpb.RecognitionConfig{
				Encoding:        speechpb.RecognitionConfig_LINEAR16,
				SampleRateHertz: 16000,
				LanguageCode:    "en-US",
			},
		},
	},
}); err != nil {
	log.Fatal(err)
}

go func() {
	// Pipe stdin to the API.
	buf := make([]byte, 1024)
	for {
		n, err := os.Stdin.Read(buf)
		if err == io.EOF {
			// Nothing else to pipe, close the stream.
			if err := stream.CloseSend(); err != nil {
				log.Fatalf("Could not close stream: %v", err)
			}
			return
		}
		if err != nil {
			log.Printf("Could not read from stdin: %v", err)
			continue
		}
		if err = stream.Send(&speechpb.StreamingRecognizeRequest{
			StreamingRequest: &speechpb.StreamingRecognizeRequest_AudioContent{
				AudioContent: buf[:n],
			},
		}); err != nil {
			log.Printf("Could not send audio: %v", err)
		}
	}
}()

for {
	resp, err := stream.Recv()
	if err == io.EOF {
		break
	}
	if err != nil {
		log.Fatalf("Cannot stream results: %v", err)
	}
	if err := resp.Error; err != nil {
		log.Fatalf("Could not recognize: %v", err)
	}
	for _, result := range resp.Results {
		fmt.Printf("Result: %+v\n", result)
	}
}

Node.js

This samples requires you to install SoX and it must be available in your $PATH.

  • For Mac OS: brew install sox.
  • For most Linux distributions: sudo apt-get install sox libsox-fmt-all.
  • For Windows: Download the binaries.

For more on installing and creating a Cloud Speech API client, refer to Cloud Speech API Client Libraries.

const record = require('node-record-lpcm16');

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

// Instantiates a client
const speech = Speech();

// The encoding of the audio file, e.g. 'LINEAR16'
// const encoding = 'LINEAR16';

// The sample rate of the audio file in hertz, e.g. 16000
// const sampleRateHertz = 16000;

// The BCP-47 language code to use, e.g. 'en-US'
// const languageCode = 'en-US';

const request = {
  config: {
    encoding: encoding,
    sampleRateHertz: sampleRateHertz,
    languageCode: languageCode
  },
  interimResults: false // If you want interim results, set this to true
};

// Create a recognize stream
const recognizeStream = speech.streamingRecognize(request)
  .on('error', console.error)
  .on('data', (data) =>
      process.stdout.write(
        (data.results[0] && data.results[0].alternatives[0])
          ? `Transcription: ${data.results[0].alternatives[0].transcript}\n`
          : `\n\nReached transcription time limit, press Ctrl+C\n`));

// Start recording and send the microphone input to the Speech API
record
  .start({
    sampleRateHertz: sampleRateHertz,
    threshold: 0,
    // Other options, see https://www.npmjs.com/package/node-record-lpcm16#options
    verbose: false,
    recordProgram: 'rec', // Try also "arecord" or "sox"
    silence: '10.0'
  })
  .on('error', console.error)
  .pipe(recognizeStream);

console.log('Listening, press Ctrl+C to stop.');

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Google Cloud Speech API Documentation