simpleaudio is another cross-platform library that’s made for playing back WAV files. A thing to note is that you can wait until the sound stops playing to continue on to the next line of code. Go ahead and install it into your environment using
pip, and just say
While that’s installing, we can head over to the text editor and try it out. So,
import simpleaudio as sa. Then define a
filename, which in my case is going to be
'hello.wav', and then make a
wave_obj, which will be
sa.WaveObject, and you’re going to make this from a WAV file, and pass in that
From here, you can go ahead and say
play_obj and make this equal to the
wave_obj and call the
.play() method off of it. And if you want to wait until that’s completed, you can then say
01:31 “Hey there, this is a WAV file.” All right! That’s pretty cool! So, WAV files are sequences of bits with metadata stored as header information. There’s always a trade-off between sound quality and file size, however, so you’ll have to decide which is more critical for your application.
01:49 WAV files are considered uncompressed, but are defined by their sample rate and the size of each sample. The standard for music on a CD is a 16-bit sample, recorded at 44,100 samples per second, but this might not be necessary for things like speech. You could, for example, drop the sampling rate down to maybe 8,000 per second and enjoy some large file size improvements.
You might be wondering what this has to do with us using Python to play sounds, and it’s a good question. Some of the libraries you’ll learn about treat audio files as bytes, while others use NumPy arrays.
simpleaudio can use both, so let’s see how this works in the editor. Go ahead and install
05:17 All right! So if you heard anything, that’s your computer generating a 440 Hz tone—or an A4 note, if you’re into music. If you’ve ever tuned a guitar off of a tuning fork, there’s a good chance that’s the note that was playing. All right!
So now you not only know how to play audio files, you can create your own audio sounds using NumPy arrays. In the next video, you’re going to learn how to use
winsound, which only works with WAV files on Windows machines.
Become a Member to join the conversation.