forked from Jasinsk/VoiceCommander
/
main.py
60 lines (42 loc) · 1.79 KB
/
main.py
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
#!/usr/bin/python
from CommandRecognizer import recognize
from CommandHandler import CommandHandler
from auditok import ADSFactory, AudioEnergyValidator, StreamTokenizer
from logger import log
from wave_utils import save_wave_file
from os import remove
import threading
import glob
def handle_command(filename):
log("Recognizing command...")
command, args = recognize(filename)
if command != 'NO_MATCH':
handler.handle(command, args)
# Delete command file since it is no longer needed
remove(filename)
def listen_for_commands(data, start, end):
log("Recorded a command.")
if 'counter' not in listen_for_commands.__dict__:
listen_for_commands.counter = 0
command_name = "command" + str(listen_for_commands.counter) + ".wav"
save_wave_file(command_name, data, samplerate=asource.get_sampling_rate(),
sample_width=asource.get_sample_width(),
channels=asource.get_channels())
threading.Thread(target=handle_command, args=(command_name,)).start()
listen_for_commands.counter += 1
log("Waiting for a command...")
if __name__=="__main__":
# Delete all .wav files
for file in glob.glob("*.wav"):
remove(file)
# Command utilities:
handler = CommandHandler()
# Auditok utilities:
asource = ADSFactory.ads(sampling_rate=16000, sample_width=2, channels=1,
frames_per_buffer=512, record=False, block_dur=0.01)
validator = AudioEnergyValidator(sample_width=asource.get_sample_width(), energy_threshold=50)
tokenizer = StreamTokenizer(validator=validator, min_length=100, max_length=500, max_continuous_silence=30)
asource.open()
# Main program loop
log("Waiting for a command...")
tokenizer.tokenize(asource, callback=listen_for_commands)