HoangHa commited on
Commit
3b0f12b
1 Parent(s): c0b0597

Upload audio_recorder.py

Browse files
Files changed (1) hide show
  1. audio_recorder.py +44 -0
audio_recorder.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pyaudio
2
+ import wave
3
+
4
+ # Set audio parameters
5
+ FORMAT = pyaudio.paInt16 # Audio format
6
+ CHANNELS = 1 # Number of audio channels
7
+ RATE = 16000 # Sampling rate
8
+ CHUNK = 1024 # Number of audio frames per buffer
9
+ RECORD_SECONDS = 10 # Duration of recording in seconds
10
+ RECORDING_FILENAME = 'recording.wav' # Name of output file
11
+
12
+
13
+ def record(seconds=RECORD_SECONDS, filename=RECORDING_FILENAME):
14
+ # Initialize PyAudio object
15
+ audio = pyaudio.PyAudio()
16
+
17
+ # Open audio stream
18
+ stream = audio.open(
19
+ format=FORMAT, channels=CHANNELS,
20
+ rate=RATE, input=True,
21
+ frames_per_buffer=CHUNK)
22
+
23
+ # Record audio
24
+ frames = []
25
+ for i in range(0, int(RATE / CHUNK * seconds)):
26
+ data = stream.read(CHUNK)
27
+ frames.append(data)
28
+
29
+ # Stop audio stream and PyAudio object
30
+ stream.stop_stream()
31
+ stream.close()
32
+ audio.terminate()
33
+
34
+ # Write frames to a WAV file
35
+ wave_file = wave.open(filename, 'wb')
36
+ wave_file.setnchannels(CHANNELS)
37
+ wave_file.setsampwidth(audio.get_sample_size(FORMAT))
38
+ wave_file.setframerate(RATE)
39
+ wave_file.writeframes(b''.join(frames))
40
+ wave_file.close()
41
+
42
+ if __name__ == '__main__':
43
+ # Run the record function with default parameters
44
+ record()