Skip to content

Commit

Permalink
docs(examples): add pyaudio streaming example (openai#1194)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot authored and stainless-app[bot] committed Feb 28, 2024
1 parent 9179a03 commit 9375d2c
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
28 changes: 27 additions & 1 deletion examples/audio.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python
#!/usr/bin/env rye run python

import time
from pathlib import Path

from openai import OpenAI
Expand All @@ -11,6 +12,8 @@


def main() -> None:
stream_to_speakers()

# Create text-to-speech audio file
with openai.audio.speech.with_streaming_response.create(
model="tts-1",
Expand All @@ -34,5 +37,28 @@ def main() -> None:
print(translation.text)


def stream_to_speakers() -> None:
import pyaudio

player_stream = pyaudio.PyAudio().open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)

start_time = time.time()

with openai.audio.speech.with_streaming_response.create(
model="tts-1",
voice="alloy",
response_format="pcm", # similar to WAV, but without a header chunk at the start.
input="""I see skies of blue and clouds of white
The bright blessed days, the dark sacred nights
And I think to myself
What a wonderful world""",
) as response:
print(f"Time to first byte: {int((time.time() - start_time) * 1000)}ms")
for chunk in response.iter_bytes(chunk_size=1024):
player_stream.write(chunk)

print(f"Done in {int((time.time() - start_time) * 1000)}ms.")


if __name__ == "__main__":
main()
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ dev-dependencies = [
"dirty-equals>=0.6.0",
"importlib-metadata>=6.7.0",
"azure-identity >=1.14.1",
"types-tqdm > 4"
"types-tqdm > 4",
"types-pyaudio > 0"
]

[tool.rye.scripts]
Expand Down
1 change: 1 addition & 0 deletions requirements-dev.lock
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ tomli==2.0.1
# via pytest
tqdm==4.66.1
# via openai
types-pyaudio==0.2.16.20240106
types-pytz==2024.1.0.20240203
# via pandas-stubs
types-tqdm==4.66.0.2
Expand Down

0 comments on commit 9375d2c

Please sign in to comment.