pydub (Part 1)
pydub is a very powerful library that can handle many different file types. Out of the box, it’s able to read and save WAV files, but you need some type of audio package to actually play sounds.
from pydub import AudioSegment, and then
from pydub.playback import play. Okay. From here, define
sound, set this equal to an
AudioSegment and call
.from_wav() off of that, and pass in a WAV file. So for me, it’s
'hello.wav'. And then you can just say
play(), and pass in that
Let’s see if this works. “Hey there, this is a WAV file.” All right, good deal! You can now play WAV files using
pydub. If you got a warning in your terminal saying that
pydub was unable to find certain libraries, that’s okay.
This is because when you import
pydub is going to look for
ffmpeg or Libav. If you want to work with other audio types like MP3s, you’re going to need one of these libraries installed.
I’ve already installed
ffmpeg, but if you’re on a Mac, you can do something like
brew install ffmpeg—which takes a while, so I’m not going to do that right now. But whatever operating system you have, you can go to FFmpeg’s documentation to see how to get it.
“Hey, this is an MP3.” And that works as well.
pydub handles many different types of files, so rather than have a
.from_mp3(), or from whatever, you can actually just say
.from_file() and then pass in whatever file type you’re trying to use.
So if I had a WMA file, I could say that there, and then you just have to pass in another argument that contains the file extension.
pydub will then look through its libraries and see if it can handle that kind of file.
pydub will also let you save files in many different formats, but we’ll cover that in the last section of this course.
We’re almost done covering different ways to play audio. In the next video, we’re going to finish up this section with
pyaudio, and then we’ll start talking about how to record audio with Python.
Become a Member to join the conversation.