Skip to content

Commit 3683c5e

Browse files
docs(examples): add pyaudio streaming example (#1194)
1 parent 9202e04 commit 3683c5e

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

examples/audio.py

+27-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env rye run python
22

3+
import time
34
from pathlib import Path
45

56
from openai import OpenAI
@@ -11,6 +12,8 @@
1112

1213

1314
def main() -> None:
15+
stream_to_speakers()
16+
1417
# Create text-to-speech audio file
1518
with openai.audio.speech.with_streaming_response.create(
1619
model="tts-1",
@@ -34,5 +37,28 @@ def main() -> None:
3437
print(translation.text)
3538

3639

40+
def stream_to_speakers() -> None:
41+
import pyaudio
42+
43+
player_stream = pyaudio.PyAudio().open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)
44+
45+
start_time = time.time()
46+
47+
with openai.audio.speech.with_streaming_response.create(
48+
model="tts-1",
49+
voice="alloy",
50+
response_format="pcm", # similar to WAV, but without a header chunk at the start.
51+
input="""I see skies of blue and clouds of white
52+
The bright blessed days, the dark sacred nights
53+
And I think to myself
54+
What a wonderful world""",
55+
) as response:
56+
print(f"Time to first byte: {int((time.time() - start_time) * 1000)}ms")
57+
for chunk in response.iter_bytes(chunk_size=1024):
58+
player_stream.write(chunk)
59+
60+
print(f"Done in {int((time.time() - start_time) * 1000)}ms.")
61+
62+
3763
if __name__ == "__main__":
3864
main()

pyproject.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ dev-dependencies = [
6161
"dirty-equals>=0.6.0",
6262
"importlib-metadata>=6.7.0",
6363
"azure-identity >=1.14.1",
64-
"types-tqdm > 4"
64+
"types-tqdm > 4",
65+
"types-pyaudio > 0"
6566
]
6667

6768
[tool.rye.scripts]

requirements-dev.lock

+1
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ tomli==2.0.1
126126
# via pytest
127127
tqdm==4.66.1
128128
# via openai
129+
types-pyaudio==0.2.16.20240106
129130
types-pytz==2024.1.0.20240203
130131
# via pandas-stubs
131132
types-tqdm==4.66.0.2

0 commit comments

Comments
 (0)