I am having trouble understanding the example program for audio recording , it comes with PyAudio module.
I am using an external Audio Card to record the sound , obviously, the voice should be converted into the digital form to be presented to the computer. But i do not understand how this code converts the input Analog Voice into Digital Form and then saving it.
Here is the code,
import pyaudio
import wave
import sys
CHUNK = 1024
# What is CHUNKS here ?
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "test.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("start....")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("done...")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
When the code is executed it record the sounds for 5seconds using an external audio card with a mic.
What I understood from the code is,
The Rate is 44Kbps, which means that 44 kilo bytes are generated from the Analog Audio signals per second.
Then an empty frame is generated frame[]
where all the recorded data will be stored.
The next thing is for
loop,
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
the answer to RATE/CHUNK*RECORD_SECONDS
is 215.33
which means there will be 215 iterations.
I don't understand why the RATE
is divided by CHUNKS
and then multiplied by RECORD_SECONDS
for the recording of 5
seconds. (RECORD_SECONDS = 5)
Also, What exactly is CHUNK
?