Skip to content

Commit 4c36236

Browse files
authored
Add files via upload
1 parent 9034e8e commit 4c36236

File tree

1 file changed

+59
-3
lines changed

1 file changed

+59
-3
lines changed

script/order_bot/order_bot.py

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# voice process modules
22
# detect voice
3-
from speech_recognition import Recognizer, Microphone
3+
from speech_recognition import Recognizer, Microphone, WavFile
4+
from pyaudio import PyAudio, paInt16
5+
import wave
46
# generate voice
57
from pygame import mixer
68
from tempfile import NamedTemporaryFile
@@ -51,7 +53,61 @@ def listener(self):
5153
print(result)
5254
return result
5355
elif self.mode == 'voice2':
54-
pass
56+
result = None
57+
while(result == None):
58+
sleep(1)
59+
# sample chunk size
60+
chunk = 1024
61+
# sample format: paFloat32, paInt32, paInt24, paInt16, paInt8, paUInt8, paCustomFormat
62+
sample_format = paInt16
63+
# sound channel
64+
channels = 2
65+
# sample frequency rate: 44100 ( CD ), 48000 ( DVD ), 22050, 24000, 12000 and 11025
66+
fs = 44100
67+
# recording seconds
68+
seconds = 5
69+
# init pyaudio object
70+
p = PyAudio()
71+
72+
print("starting recording...")
73+
74+
# active voice stream
75+
stream = p.open(format=sample_format, channels=channels, rate=fs, frames_per_buffer=chunk, input=True)
76+
frames = []
77+
# voice list
78+
for _ in range(0, int(fs / chunk * seconds)):
79+
# record voice into list
80+
data = stream.read(chunk)
81+
frames.append(data)
82+
# stop recording
83+
stream.stop_stream()
84+
# close stream
85+
stream.close()
86+
p.terminate()
87+
print('stop recording...')
88+
89+
90+
with NamedTemporaryFile(delete=True) as fp:
91+
# open voice file
92+
wf = wave.open("{}.wav".format(fp.name), 'wb')
93+
# set channel
94+
wf.setnchannels(channels)
95+
# set format
96+
wf.setsampwidth(p.get_sample_size(sample_format))
97+
# set sampling frequency rate
98+
wf.setframerate(fs)
99+
# save
100+
wf.writeframes(b''.join(frames))
101+
wf.close()
102+
103+
with WavFile('{}.wav'.format(fp.name)) as source:
104+
audio = self.recognizer.listen(source)
105+
try:
106+
result = self.recognizer.recognize_google(audio,language = 'zh-tw')
107+
except:
108+
continue
109+
print(result)
110+
return result
55111

56112
def order_manage(self):
57113
data_dict = load_xlsx(file_name=menu_xlsx_path)
@@ -130,5 +186,5 @@ def __call__(self):
130186

131187
if __name__ == '__main__':
132188
order_bot = Order_Bot('text')
133-
order_bot.mode = 'voice1'
189+
order_bot.mode = 'voice2'
134190
order_bot()

0 commit comments

Comments
 (0)