Skip to content

Commit 441d35f

Browse files
authored
Add files via upload
1 parent 7858f38 commit 441d35f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

recording_voice.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import pyaudio
2+
import wave
3+
4+
class Recording_Helper:
5+
def __init__(self, chunk = 1024, sample_format = pyaudio.paInt16, channels = 2, fs = 44100, seconds = 5, filename = "test.wav"):
6+
# sample chunk size
7+
self.chunk = chunk
8+
# sample format: paFloat32, paInt32, paInt24, paInt16, paInt8, paUInt8, paCustomFormat
9+
self.sample_format = sample_format
10+
# sound channel
11+
self.channels = channels
12+
# sample frequency rate: 44100 ( CD ), 48000 ( DVD ), 22050, 24000, 12000 and 11025
13+
self.fs = fs
14+
# recording seconds
15+
self.seconds = seconds
16+
# recording file name
17+
self.filename = filename
18+
19+
self.p = pyaudio.PyAudio()
20+
# init pyaudio object
21+
22+
def recording_voice(self):
23+
print("starting recording...")
24+
25+
# active voice stream
26+
stream = self.p.open(format=self.sample_format, channels=self.channels, rate=self.fs, frames_per_buffer=self.chunk, input=True)
27+
28+
frames = []
29+
# voice list
30+
31+
for i in range(0, int(self.fs / self.chunk * self.seconds)):
32+
# record voice into list
33+
data = stream.read(self.chunk)
34+
frames.append(data)
35+
36+
# stop recording
37+
stream.stop_stream()
38+
# close stream
39+
stream.close()
40+
self.p.terminate()
41+
42+
print('stop recording...')
43+
44+
# open voice file
45+
wf = wave.open(self.filename, 'wb')
46+
# set channel
47+
wf.setnchannels(self.channels)
48+
# set format
49+
wf.setsampwidth(self.p.get_sample_size(self.sample_format))
50+
# set sampling frequency rate
51+
wf.setframerate(self.fs)
52+
# save
53+
wf.writeframes(b''.join(frames))
54+
wf.close()

0 commit comments

Comments
 (0)