|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright 2024 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | + |
| 17 | +"""Google Cloud Text-To-Speech API streaming sample application . |
| 18 | +
|
| 19 | +Example usage: |
| 20 | + python streaming_tts_quickstart.py |
| 21 | +""" |
| 22 | + |
| 23 | + |
| 24 | +def run_streaming_tts_quickstart(): |
| 25 | + # [START tts_synthezise_streaming] |
| 26 | + """Synthesizes speech from a stream of input text. |
| 27 | + """ |
| 28 | + from google.cloud import texttospeech |
| 29 | + import itertools |
| 30 | + |
| 31 | + client = texttospeech.TextToSpeechClient() |
| 32 | + |
| 33 | + # See https://cloud.google.com/text-to-speech/docs/voices for all voices. |
| 34 | + streaming_config = texttospeech.StreamingSynthesizeConfig(voice=texttospeech.VoiceSelectionParams(name="en-US-Journey-D", language_code="en-US")) |
| 35 | + |
| 36 | + # Set the config for your stream. The first request must contain your config, and then each subsequent request must contain text. |
| 37 | + config_request = texttospeech.StreamingSynthesizeRequest(streaming_config=streaming_config) |
| 38 | + |
| 39 | + # Request generator. Consider using Gemini or another LLM with output streaming as a generator. |
| 40 | + def request_generator(): |
| 41 | + yield texttospeech.StreamingSynthesizeRequest(input=texttospeech.StreamingSynthesisInput(text="Hello there. ")) |
| 42 | + yield texttospeech.StreamingSynthesizeRequest(input=texttospeech.StreamingSynthesisInput(text="How are you ")) |
| 43 | + yield texttospeech.StreamingSynthesizeRequest(input=texttospeech.StreamingSynthesisInput(text="today? It's ")) |
| 44 | + yield texttospeech.StreamingSynthesizeRequest(input=texttospeech.StreamingSynthesisInput(text="such nice weather outside.")) |
| 45 | + |
| 46 | + streaming_responses = client.streaming_synthesize(itertools.chain([config_request], request_generator())) |
| 47 | + for response in streaming_responses: |
| 48 | + print(f"Audio content size in bytes is: {len(response.audio_content)}") |
| 49 | + # [END tts_synthezise_streaming] |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + run_streaming_tts_quickstart() |
0 commit comments