-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathRecorder.py
61 lines (45 loc) · 1.87 KB
/
Recorder.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
import pyaudio
import wave
def record_audio(RECORD_SECONDS, WAVE_OUTPUT_FILENAME):
#--------- SETTING PARAMS FOR OUR AUDIO FILE ------------#
FORMAT = pyaudio.paInt16 # format of wave
CHANNELS = 2 # no. of audio channels
RATE = 44100 # frame rate
CHUNK = 1024 # frames per audio sample
#--------------------------------------------------------#
# creating PyAudio object
audio = pyaudio.PyAudio()
# open a new stream for microphone
# It creates a PortAudio Stream Wrapper class object
stream = audio.open(format=FORMAT,channels=CHANNELS,
rate=RATE, input=True,
frames_per_buffer=CHUNK)
#----------------- start of recording -------------------#
print("Listening...")
# list to save all audio frames
frames = []
for i in range(int(RATE / CHUNK * RECORD_SECONDS)):
# read audio stream from microphone
data = stream.read(CHUNK)
# append audio data to frames list
frames.append(data)
#------------------ end of recording --------------------#
print("Finished recording.")
stream.stop_stream() # stop the stream object
stream.close() # close the stream object
audio.terminate() # terminate PortAudio
#------------------ saving audio ------------------------#
# create wave file object
waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
# settings for wave file object
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
# closing the wave file object
waveFile.close()
def read_audio(WAVE_FILENAME):
# function to read audio(wav) file
with open(WAVE_FILENAME, 'rb') as f:
audio = f.read()
return audio