-
Notifications
You must be signed in to change notification settings - Fork 1
Feature/TTS with streaming demo #55
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lgavincrl
wants to merge
17
commits into
main
Choose a base branch
from
feature/tts-streaming-demo
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+187
−17
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
7b20c04
TTS with streaming audio
lgavincrl d1db50f
fix tts init formatting
lgavincrl 67c7005
gitignore update
lgavincrl 5157bb2
code tidy
lgavincrl 57e7eaa
TTS Streaming example, info & corrections
lgavincrl 4fbffc4
TTS stream README file
lgavincrl cb2e3ee
TTS streaming README correction
lgavincrl cf89a03
git ignore
lgavincrl e994263
Add "Jack"
lgavincrl ec6a0ed
tts stream example with Jack
lgavincrl ed8e1c4
Apply suggestion from @TudorCRL
lgavincrl 622e339
example - format correction
lgavincrl 48e1acb
File deletion
lgavincrl f62383e
gitignore corrections
lgavincrl 3b63bb7
Streaming eg readme updates
lgavincrl 8a8532a
TTS readme correction
lgavincrl 496d712
RT format correction
lgavincrl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # Speechmatics TTS Async Streaming API Client | ||
|
|
||
| This example shows how to use the Speechmatics TTS API to generate audio from text and autoplay it using sounddevice through the systems default audio output device. | ||
| You must have an audio output device configured on their system for this example to work. | ||
| ## How it Works | ||
|
|
||
| There are two main components in this example, an audio generator and an audio player. These components are run concurrently using asyncio as tasks, ochestrated by the main() function, to generate and play audio in real-time. | ||
| ### audio_generator() | ||
|
|
||
| This producer function connects to the Speechmatics TTS API using the AsyncClient. It calls client.generate() with your text, the voice you want to use, and the output format - RAW_PCM_16000 in this example. | ||
| The code iterates over the audio data as it is streamed in chunks (iter_chunked), and accumulates in a bytearray buffer. | ||
| The while len(buffer) >= 2 loop reads each audio sample containing 2 bytes, from the buffer, and converts it to a numpy array of int-16 values, which is then put into the audio_queue. | ||
| The processed 2 byte sample is then removed from the front of the buffer. | ||
| END_OF_STREAM is used as a sentinel value to signal the end of the audio stream, with no more audio data to process. | ||
| If an error occurs during audio generation, the END_OF_STREAM sentinel value is still put into the queue to signal the end of the audio stream to prevent the consumer, audio_player(), from getting stuck in an infinite loop, and raises the exception. | ||
| ### audio_player() | ||
|
|
||
| This consumer function initialises a sounddevice OutputStream, which is responsible for streaming the audio data to the default audio output device. Within the outputstream, the while True loop means there is continous processing of the incoming audio data. | ||
| sample = await asyncio.wait_for(play_queue.get(), timeout=0.1) fetches the next sample from the queue, or waits for 0.1 seconds if the queue is empty. | ||
| If the sample is END_OF_STREAM, the while loop breaks and the audio player exits. | ||
| If the sample is not END_OF_STREAM, it is converted to a numpy array of int-16 values and written to the audio output device using the sounddevice OutputStream. | ||
| play_queue.task_done() is called to signal that the sample has been processed. | ||
| If an error occurs during audio playback, the END_OF_STREAM sentinel value is still put into the queue to signal the end of the audio stream to prevent the audio_player() from getting stuck in an infinite loop, and raises the exception. | ||
|
|
||
| ## Installation | ||
|
|
||
| ```bash | ||
| pip install speechmatics-tts | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| To run the example, use the following command: | ||
|
|
||
| ```bash | ||
| python tts_stream_example.py | ||
| ``` | ||
|
|
||
| ## Environment Variables | ||
|
|
||
| The client supports the following environment variables: | ||
|
|
||
| - `SPEECHMATICS_API_KEY`: Your Speechmatics API key |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| sounddevice>=0.4.6 | ||
| numpy>=1.24.3 | ||
| speechmatics-tts>=0.1.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| import asyncio | ||
| import sounddevice as sd | ||
| import numpy as np | ||
| from speechmatics.tts import AsyncClient, Voice, OutputFormat | ||
|
|
||
| # Configuration | ||
| TEXT = "Welcome to the future of audio generation from text! This audio is a demo of the async streaming Speechmatics Text-to-Speech (TTS) API." | ||
| VOICE = Voice.JACK | ||
| OUTPUT_FORMAT = OutputFormat.RAW_PCM_16000 | ||
|
|
||
| # Audio Parameters | ||
| SAMPLE_RATE = 16000 #Hz | ||
| SAMPLE_WIDTH = 2 # 16-bit audio | ||
| CHANNELS = 1 # Mono audio | ||
| CHUNK_SIZE = 2048 # Size of audio chunks | ||
| BUFFER_SIZE = 4096 # Size of buffer | ||
|
|
||
| # Sentinel value to signal end of stream | ||
| END_OF_STREAM = None | ||
|
|
||
|
|
||
| # Core Async Functions | ||
|
|
||
| # 1. Producer: Generates audio and puts chunks into the queue: | ||
|
|
||
| async def audio_generator(audio_queue: asyncio.Queue, text: str, voice: str, output_format: str) -> None: | ||
| # Generate speech and stream audio chunks into the queue. | ||
|
|
||
| try: | ||
| async with AsyncClient() as client, await client.generate( | ||
| text=text, | ||
| voice=voice, | ||
| output_format=output_format | ||
| ) as response: | ||
| buffer=bytearray() | ||
| async for chunk in response.content.iter_chunked(BUFFER_SIZE): | ||
| if not chunk: | ||
| continue | ||
| buffer.extend(chunk) | ||
|
|
||
| # Process complete frames (2 bytes per sample for 16-bit audio) | ||
| # Convert little-endian 16-bit signed int to np.int-16 | ||
| while len(buffer) >= 2: | ||
| sample = int.from_bytes(buffer[:2], byteorder='little', signed=True) | ||
| await audio_queue.put(sample) | ||
| buffer = buffer[2:] | ||
|
|
||
| await audio_queue.put(END_OF_STREAM) | ||
| print("Audio generated and put into queue.") | ||
|
|
||
| except Exception as e: | ||
| print(f"[{'Generator'}] An error occurred in the audio generator: {e}") | ||
| await audio_queue.put(END_OF_STREAM) | ||
| raise | ||
|
|
||
| # 2. Consumer: Read audio data from queue and play it in real-time using sounddevice. | ||
| async def audio_player(play_queue: asyncio.Queue) -> None: | ||
| try: | ||
| with sd.OutputStream( | ||
| samplerate=SAMPLE_RATE, | ||
| channels=CHANNELS, | ||
| dtype='int16', # 16-bit PCM | ||
| blocksize=CHUNK_SIZE, | ||
| latency='high', | ||
| ) as stream: | ||
| buffer=[] | ||
| while True: | ||
| try: | ||
| sample = await asyncio.wait_for(play_queue.get(), timeout=0.1) | ||
| if sample is END_OF_STREAM: | ||
| if buffer: | ||
| audio_data=np.array(buffer, dtype=np.int16) | ||
| stream.write(audio_data) | ||
| buffer=[] | ||
| break | ||
|
|
||
| buffer.append(sample) | ||
| if len(buffer) >= CHUNK_SIZE: | ||
| audio_data=np.array(buffer[:CHUNK_SIZE], dtype=np.int16) | ||
| stream.write(audio_data) | ||
| buffer=buffer[CHUNK_SIZE:] | ||
|
|
||
| play_queue.task_done() | ||
|
|
||
| except asyncio.TimeoutError: | ||
| if buffer: | ||
| audio_data=np.array(buffer, dtype=np.int16) | ||
| stream.write(audio_data) | ||
| buffer=[] | ||
| continue | ||
|
|
||
| except Exception as e: | ||
| print(f"[{'Player'}] An error occurred playing audio chunk {e}") | ||
| raise | ||
|
|
||
| except Exception as e: | ||
| print(f"[{'Player'}] An error occurred in the audio player: {e}") | ||
| raise | ||
| finally: | ||
| sd.stop() | ||
|
|
||
| # 3. Main Function: Orchestrate audio generation and audio stream | ||
| async def main() -> None: | ||
| play_queue = asyncio.Queue() | ||
|
|
||
| # Create tasks | ||
| tasks = [ | ||
| asyncio.create_task(audio_generator(play_queue, TEXT, VOICE, OUTPUT_FORMAT)), | ||
| asyncio.create_task(audio_player(play_queue)) | ||
| ] | ||
|
|
||
| try: | ||
| await asyncio.gather(*tasks) | ||
|
|
||
| except Exception as e: | ||
| for task in tasks: | ||
| task.cancel() | ||
| await asyncio.gather(*tasks, return_exceptions=True) | ||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,4 +26,4 @@ | |
| "ConnectionConfig", | ||
| "Voice", | ||
| "OutputFormat", | ||
| ] | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.