Before we get started, have you tried our new Python Code Assistant? It's like having an expert coder at your fingertips. Check it out!
Many of the applications out there record your voice as well as playing sounds, if you want to do that as well, then you came into the right place, in this tutorial, we will be using different Python libraries to play and record audio in Python.
Let's install the required libraries for this tutorial:
First, we gonna start with the most straightforward module here, playsound:
Yes, that's it for this module. It is basically a pure Python, cross-platform, single-function module. The documentation says that WAV and MP3 extensions are known to work, and they may work for other formats as well.
The playsound() function plays the sound in the audio file and blocks until the file reading is completed; you can pass block=False to make the function run asynchronously.
Another alternative is to use the Pydub library:
Note: You need FFmpeg installed on your machine in order to use AudioSegment.from_file() function that supports all formats that are supported by FFmpeg.
Pydub is quite a popular library, as it isn't only for playing sound, you can use it for different purposes, such as converting audio files, slicing audio, boosting or reducing volume, and much more, check their repository for more information.
If you wish to play audio using PyAudio, check this link.
Related: How to Extract Audio from Video in Python.
To record voice, we gonna use the PyAudio library, as it is the most convenient approach:
The above code basically initializes the PyAudio object, and then we open up a stream object that allows us to record from the microphone using stream.read() method. After we finish recording, we use the built-in wave module to write that WAV audio file into the disk.
When you set input=True in the p.open() method, you will be able to use stream.read() to read from the microphone. Also, when you set output=True, you'll be able to use stream.write() to write to the speaker.
Alright, in this tutorial, you learned how you can play audio files using playsound, Pydub, and PyAudio libraries as well as recording voice using PyAudio.
A great challenge for you is to combine this with a screen recorder, and you'll come up with a Python tool that records your voice and screen simultaneously. You will need to use a thread that records audio and another one for the screen recorder, good luck with that!
Learn also: How to Convert Text to Speech in Python.
Happy Coding ♥
Liked what you read? You'll love what you can learn from our AI-powered Code Explainer. Check it out!
View Full Code Assist My Coding
Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!