Skip to content
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

docs(examples): add pyaudio streaming example #1194

Merged
merged 1 commit into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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