openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.23.6

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/audio.py

64lines · modeblame

9375d2ccStainless Bot2 years ago1#!/usr/bin/env rye run python
e9c26d1eStainless Bot2 years ago2
9375d2ccStainless Bot2 years ago3import time
e9c26d1eStainless Bot2 years ago4from pathlib import Path
5
6from openai import OpenAI
7
8# gets OPENAI_API_KEY from your environment variables
9openai = OpenAI()
10
11speech_file_path = Path(__file__).parent / "speech.mp3"
12
13
14def main() -> None:
9375d2ccStainless Bot2 years ago15stream_to_speakers()
16
e9c26d1eStainless Bot2 years ago17# Create text-to-speech audio file
86379b44Stainless Bot2 years ago18with openai.audio.speech.with_streaming_response.create(
19model="tts-1",
20voice="alloy",
21input="the quick brown fox jumped over the lazy dogs",
22) as response:
23response.stream_to_file(speech_file_path)
e9c26d1eStainless Bot2 years ago24
25# Create transcription from audio file
86379b44Stainless Bot2 years ago26transcription = openai.audio.transcriptions.create(
27model="whisper-1",
28file=speech_file_path,
29)
e9c26d1eStainless Bot2 years ago30print(transcription.text)
31
32# Create translation from audio file
33translation = openai.audio.translations.create(
34model="whisper-1",
35file=speech_file_path,
36)
37print(translation.text)
38
39
9375d2ccStainless Bot2 years ago40def stream_to_speakers() -> None:
41import pyaudio
42
43player_stream = pyaudio.PyAudio().open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)
44
45start_time = time.time()
46
47with openai.audio.speech.with_streaming_response.create(
48model="tts-1",
49voice="alloy",
50response_format="pcm", # similar to WAV, but without a header chunk at the start.
51input="""I see skies of blue and clouds of white
52The bright blessed days, the dark sacred nights
53And I think to myself
54What a wonderful world""",
55) as response:
56print(f"Time to first byte: {int((time.time() - start_time) * 1000)}ms")
57for chunk in response.iter_bytes(chunk_size=1024):
58player_stream.write(chunk)
59
60print(f"Done in {int((time.time() - start_time) * 1000)}ms.")
61
62
e9c26d1eStainless Bot2 years ago63if __name__ == "__main__":
64main()