-
Notifications
You must be signed in to change notification settings - Fork 16
/
recordSpeech.py
109 lines (88 loc) · 2.64 KB
/
recordSpeech.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import pyaudio
import os
import wave
import time
FORMAT = pyaudio.paInt16
# Keep number of channel one to avoid errors in speech api like retry error
CHANNELS = 1
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 10
WAVE_OUTPUT_FILENAME = "file.wav"
FLAC_OUTPUT_FILENAME = 'file.flac'
PATH_TO_AUDIO_FILE = os.path.dirname(os.path.abspath(__file__))
frames = []
record_on = False
def callback(in_data, frame_count, time_info, status):
if record_on:
global frames
frames.append(in_data)
callback_flag = pyaudio.paContinue
else:
callback_flag = pyaudio.paComplete
return (in_data, callback_flag)
def record_audio():
global frames
frames = []
audio = pyaudio.PyAudio()
'''
#start recording without callback
stream = audio.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("Please say something......")
while record_on:
data = stream.read(CHUNK)
frames.append(data)
'''
# starts Recording with callback
stream = audio.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
stream_callback=callback)
print("Please say something......")
stream.start_stream()
while stream.is_active():
time.sleep(0.1)
print("Thank you for Input")
# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()
# get current directory and save recorded file in that directory
path = PATH_TO_AUDIO_FILE
path = path + '\\' + WAVE_OUTPUT_FILENAME
print(path)
waveFile = wave.open(path, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()
"""
play = pyaudio.PyAudio()
stream_play = play.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
output=True)
# Gives Output of recording
for data in frames:
stream_play.write(data)
stream_play.stop_stream()
stream_play.close()
play.terminate()
"""
def set_path_to_audio_file(path):
global PATH_TO_AUDIO_FILE
PATH_TO_AUDIO_FILE = path
# executes this code if script is executed directly in cmd or pycharm
if __name__ == "__main__":
record_on = True
record_audio()
time.sleep(5)
record_on = False
pass