Skip to content

Commit

Permalink
Add Websocket code snippet to README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
fern-bot committed Nov 14, 2024
1 parent 533f2f2 commit 93ddbfa
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,61 @@ for chunk in response:
yield chunk
```

## WebSocket

```python
from cartesia import Cartesia
from cartesia.tts import TtsRequestEmbeddingSpecifier, OutputFormat_Raw
import pyaudio

client = Cartesia(
api_key_header="YOUR_API_KEY_HEADER",
)
voice_id = "a0e99841-438c-4a64-b679-ae501e7d6091"
voice = client.voices.get(id=voice_id)
transcript = "Hello! Welcome to Cartesia"

# You can check out our models at https://docs.cartesia.ai/getting-started/available-models
model_id = "sonic-english"

# You can find the supported `output_format`s at https://docs.cartesia.ai/reference/api-reference/rest/stream-speech-server-sent-events
output_format = OutputFormat_Raw(
container="raw",
encoding="pcm_f32le",
sample_rate=22050
)

p = pyaudio.PyAudio()
rate = 22050

stream = None

# Set up the websocket connection
ws = client.tts.websocket()

# Generate and stream audio using the websocket
for output in ws.send(
model_id=model_id,
transcript=transcript,
voice=TtsRequestEmbeddingSpecifier(embedding=voice.embedding),
stream=True,
output_format=output_format,
):
buffer = output.audio

if not stream:
stream = p.open(format=pyaudio.paFloat32, channels=1, rate=rate, output=True)

# Write the audio data to the stream
stream.write(buffer)

stream.stop_stream()
stream.close()
p.terminate()

ws.close() # Close the websocket connection
```

## Advanced

### Retries
Expand Down

0 comments on commit 93ddbfa

Please sign in to comment.