python-sounddevice (Part 2)
python-sounddevice is going to record audio from your microphone and store it as a NumPy array. If you’d like to convert a NumPy array to a WAV file, you’ll want to use a module from
SciPy to do so. Let’s go ahead and install
SciPy to get started.
Going to the text editor, you’re going to
import sounddevice as sd, and then
from scipy.io.wavfile, and you’ll just want to
import write. So before, when we were playing audio,
python-sounddevice obtained a lot of information from the WAV file itself. Since you’re going to be creating a WAV file, you’ll need to set a sample rate, so using
fs set the sample rate to
44100, and then a duration, so
seconds, and let’s go
3. Now it’s time to create the recording object, so just go ahead and say something like
myrecording and equal this to
sd.rec() (record), and pass in an integer of
seconds times your sample rate.
You’ll want to wait until the recording is complete before you write anything, so throw in
sd.wait(), and then go ahead and
write(), and we’ll just call this
'output.wav'. And you’ll want to pass it in your sample rate, and then that actual recording object.
Let’s run that again and see if it worked. “And we’ll see if this records.” Awesome! So that went to the microphone on my laptop, but you can see that we were able to record something using
Pretty cool! So,
python-sounddevice is a good high-level recording option to use. In the next video, we’re going to take a look at
pyaudio, which you may remember was a little bit more complex, but a very powerful library for dealing with audio in Python.
Become a Member to join the conversation.