Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

python-sounddevice (Part 1)

00:00 python-sounddevice provides bindings for the PortAudio library and a few convenience functions to play and record NumPy arrays containing audio signals. Because of this, it has a few dependencies to open WAV files and work with NumPy arrays.

00:14 You should already have NumPy installed from earlier, but just to be safe, let’s go ahead and install NumPy and soundfile.

00:26 python-sounddevice will need NumPy to work with NumPy arrays, and then we’re going to use soundfile to actually read in the WAV files.

00:40 While that’s going, we can go to the text editor and import sounddevice and soundfile. import sounddevice as sd, and then import soundfile as sf.

00:57 Like before, go ahead and define your filename. So for me, 'hello.wav'.

01:03 Then you’re going to want to save the data and the sampling rate from that WAV file. So set data and fs equal to sf.read(), and then you’re going to pass in the filename and then a dtype (data type), for which you’ll just want 'float32'. soundfile.read() is going to read the audio data from that WAV file and then also take a look at the headers to get that sampling rate for you.

01:31 All right. So once you have these defined, you can call sd and just say play(). Pass in data and that sampling rate.

01:40 And then if you wanted to use the status later on, you could say sd.wait(), and that will make sure that the sound has finished playing before the script is terminated. So let’s try this out.

01:54 I’m going save this. And, of course, we installed the dependencies for sounddevice but not sounddevice itself, so let’s go ahead and grab that.

02:15 There we go. Try again. “Hey there, this is a WAV file.” All right, that worked! Now you should know how to use python-sounddevice to play files, and you’ll see later on, you can actually use this library to record sound as well. In the next video, you’re going to learn how to use pydub, which handles quite a few different audio formats.

02:37 It can be a little tricky to set up, so we’ll cover that too. Thanks for watching.

Become a Member to join the conversation.