-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathaudioResponse.py
More file actions
69 lines (53 loc) · 2 KB
/
audioResponse.py
File metadata and controls
69 lines (53 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import wave
import subprocess
import pika # needed to send messages out via RabbitMQ
from piper.voice import PiperVoice
class AudioResponse:
"""
Class that handles generating and streaming audio messages made from text input
"""
def __init__(self):
"""
Initialization method
"""
# load Piper TTS voice model
self.voice = PiperVoice.load("en_US-amy-medium.onnx")
# set up RabbitMQ
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
self.channel = self.connection.channel()
self.channel.queue_declare(queue='audioInput')
self.channel.basic_consume(queue='audioInput', on_message_callback=self.audioCallback, auto_ack=True)
def startListening(self):
"""
starts the listener thread
"""
print("Beginning RabbitMQ listener")
self.channel.start_consuming()
def audioCallback(self, ch, method, properties, body):
"""
Callback method for audio out queue, turning text into speech
Args:
ch (_type_): _description_
method (_type_): _description_
properties (_type_): _description_
body (str): message from the llm
"""
text = body.decode()
self.textToSpeech(text=text)
def textToSpeech(self, text):
"""
Turns the provided text into audio and plays it
Args:
text (str): The text to turn to audio
"""
# generate audio via Piper TTS
with wave.open("response.wav", "wb") as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2) # 16-bit audio
wav_file.setframerate(self.voice.config.sample_rate)
self.voice.synthesize_wav(str(text), wav_file)
# plays the response and waits for it to finish
subprocess.run(['aplay', 'response.wav'], check=True)
if __name__ == '__main__':
audioResp = AudioResponse()
audioResp.startListening()