pyaudio (Part 2)
Now it’s time to take a look at recording sound using
pyaudio. Like before, you can expect this to use quite a few more lines of code than
python-sounddevice. Let’s jump into the editor and get started. First, go ahead and make your imports, so we want
pyaudio and also
Now it’s time to set some attributes.
chunk, like before, will be
sample_format is going to equal
pyaudio.paInt16, which just sets it to 16 bits per sample. For
channels, you’re going to want
2 to get a stereo. And set the sample rate.
And I’ve gone and deleted the
output.wav from the previous example. All right. So now you want to make that PortAudio interface, so set
p = pyaudio.PyAudio(), and so that we know that we’re recording, you can just print out something like
And now this time, you’ll set
input=True, and this is what will tell
pyaudio that we’re going to be recording. Now that you have that, go ahead and make an empty list called
frames to collect the data frames that will be recorded.
You’re going to want to store data in those chunks for three seconds, and you can do this with a
for loop. So,
for i in range(), and you want to start at
0 and then make an integer from the sample rate divided by the
Once you have that, take your
frames list and append that data frame. When that loop is finished, you’ll no longer be recording. At this point, you can take your
stream and you can stop the stream.
You can also close the stream. And, like before, you’re going to want to terminate that interface to PortAudio. So now everything related to the recording is completed, so you can print out
'Finished recording...', and you’re left with that list of data frames.
And then you’ll want to set those attributes that you defined earlier, so
.setnchannels() is going to equal
.setsampwidth() (set the sample width) is going to be
p.get_sample_size(), and then you’ll pass in that
sample_format. And then set the frame rate,
and you’ll make a byte string, which you’ll then just join all of the data from that
frames list. And close the file. So, you can see from writing to the file that we’re doing things kind of backwards from playing audio. Now instead of getting these attributes from the file itself, you’re setting these attributes. All right, let’s see if it works!
“This is recording with
pyaudio.” It worked! Now you have two solid ways to record audio in your projects. Both of these produced WAV files, however, so if you want to make MP3s or use other audio formats, you’ll want to be able to convert them.
Become a Member to join the conversation.