1212
1313from deepgram import DeepgramClient
1414from deepgram .core .events import EventType
15- from deepgram .speak .v1 .types import SpeakV1Text , SpeakV1Flush , SpeakV1Close
15+ from deepgram .speak .v1 .types import SpeakV1Close , SpeakV1Flush , SpeakV1Text
1616
1717SpeakV1SocketClientResponse = Union [str , bytes ]
1818
1919client = DeepgramClient ()
2020
2121try :
2222 with client .speak .v1 .connect (model = "aura-2-asteria-en" , encoding = "linear16" , sample_rate = 24000 ) as connection :
23+
2324 def on_message (message : SpeakV1SocketClientResponse ) -> None :
2425 if isinstance (message , bytes ):
2526 print ("Received audio data" )
@@ -29,7 +30,7 @@ def on_message(message: SpeakV1SocketClientResponse) -> None:
2930 else :
3031 msg_type = getattr (message , "type" , "Unknown" )
3132 print (f"Received { msg_type } event" )
32-
33+
3334 connection .on (EventType .OPEN , lambda _ : print ("Connection opened" ))
3435 connection .on (EventType .MESSAGE , on_message )
3536 connection .on (EventType .CLOSE , lambda _ : print ("Connection closed" ))
@@ -40,19 +41,19 @@ def on_message(message: SpeakV1SocketClientResponse) -> None:
4041 # For better control with bidirectional communication, use the async version
4142 text_message = SpeakV1Text (text = "Hello, this is a text to speech example." )
4243 connection .send_speak_v_1_text (text_message )
43-
44+
4445 # Flush to ensure all text is processed
4546 flush_message = SpeakV1Flush ()
4647 connection .send_speak_v_1_flush (flush_message )
47-
48+
4849 # Close the connection when done
4950 close_message = SpeakV1Close ()
5051 connection .send_speak_v_1_close (close_message )
51-
52+
5253 # Start listening - this blocks until the connection closes
5354 # All messages should be sent before calling this in sync mode
5455 connection .start_listening ()
55-
56+
5657 # For async version:
5758 # from deepgram import AsyncDeepgramClient
5859 # async with client.speak.v1.connect(...) as connection:
@@ -61,7 +62,6 @@ def on_message(message: SpeakV1SocketClientResponse) -> None:
6162 # await connection.send_speak_v_1_flush(SpeakV1Flush())
6263 # await connection.send_speak_v_1_close(SpeakV1Close())
6364 # await listen_task
64-
65+
6566except Exception as e :
6667 print (f"Error: { e } " )
67-
0 commit comments