openai/openai-python

Public

mirrored fromhttps://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1bdabb489a86bd721a3e237d8556583ed0d8dfa1

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/audio.py

64lines · modecode

1#!/usr/bin/env rye run python
2
3import time
4from 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:
15 stream_to_speakers()
16
17 # Create text-to-speech audio file
18 with openai.audio.speech.with_streaming_response.create(
19 model="tts-1",
20 voice="alloy",
21 input="the quick brown fox jumped over the lazy dogs",
22 ) as response:
23 response.stream_to_file(speech_file_path)
24
25 # Create transcription from audio file
26 transcription = openai.audio.transcriptions.create(
27 model="whisper-1",
28 file=speech_file_path,
29 )
30 print(transcription.text)
31
32 # Create translation from audio file
33 translation = openai.audio.translations.create(
34 model="whisper-1",
35 file=speech_file_path,
36 )
37 print(translation.text)
38
39
40def 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
63if __name__ == "__main__":
64 main()