How to Play and Record Audio in Python?

Posted in /  

How to Play and Record Audio in Python?
vinaykhatri

Vinay Khatri
Last updated on October 31, 2024

    There are many applications out there on the internet that can play and record audio files such as mp3, wav, and mp4. If you are a Python developer and wish to write code that can record or play audio for you, then continue reading this article.

    In this Python tutorial, I will walk you through two Python programs that can play and record audio.

    How to Play and Record Audio in Python?

    Install Required Libraries

    Before we can code in Python to play and record audio, we need to install three Python libraries, namely playsound, sounddevice, and Scipy.

    1) Python playsound library

    As the library name suggests, the playsound library is used to play different types of audio files. It is an open-source Python library, and you can install it using the following pip command:

    pip install playsound

    2) Python sounddevice library

    The Python sounddevice library is another open-source library that is used to play and record NumPy arrays containing sound singles. This means it uses NumPy arrays to generate and structure audio file data. To install the sounddevice library, run the following pip command on your terminal or command prompt:

    pip install sounddevice

    3) Python Scipy library

    Scipy is a scientific computing library for Python, and in this tutorial, we will be using this library to save or write the data generated by the sounddevice library. Install the Python library using the following command:

    install numpy scipy

    Python Program to Play Audio Files

    Playing an audio file is very straightforward with the Python playsound library. Check out the following code:

    from playsound import playsound
    
    filename = "music.mp3"
    
    print(f"Playing {filename}..............................")
    playsound(filename)  #play audio

    Output

    Playing music.mp3..............................

    In this example, the music.mp3 audio file is located in the same directory where the Python script is, and that's why we have only specified the file name, not the complete path.

    Thus, if your audio file is located in some directory other than the directory having the Python script, then you need to specify the full path, like: filename =r"C:\Users\tsmehra\music\music.mp3"

    How to Record Audio in Python?

    Now you know how to play audio in Python using the Python playsound library. Next, let's write a Python program that will record audio from your mic. Let's start with importing the required modules.

    import sounddevice as sd  
    from scipy.io.wavfile import write
    from playsound import playsound
    import time

    With the sounddevice module, we will record the audio in the wav format. Using the scipy.io.wavfile write module, we will save the recorded wav audio file locally, and the playsound module will allow us to play the recorded file. With the time module, we will create a recording timer.

    Now, let's define a timer function that will print the timer while the audio is recording.

    def timer(duration):
        while duration: 
            mins, secs = divmod(duration, 60) 
            timer = f"{mins} mins:{secs} seconds Left"
            print(timer, end=" \r") 
            time.sleep(1) 
            duration -= 1

    Next, let's define the audio_record function that will record the audio and save it locally:

    def record_audio(filename):
        
        #frequency
        fs=44100  #frames per second  
        duration = 10  # seconds in integer
        
        print("Recording..........")
    
        #start recording 
        myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=2)
    
        timer(duration)    #call timer function
        sd.wait()
    
        #write the data in filename and save it
        write(filename, fs, myrecording)

    The fs variable specifies the frequency of the audio in frames per second, and its value could either be 44,100 or  48,000. The duration variable defines the recording duration in seconds.

    rec() initializes the recording object while the wait() function holds the recording screen for the specified duration . Also, the write() function writes the recorded data and saves it in the same directory where the Python script is located, with the specified filename .

    Now, let's declare a variable that represents the recorded audio file name and calls the record_audio function.

    filename ="new_record.wav"
    record_audio(filename)
    
    listen = input("Do you want to listen the recorded audio? [y/n]")
    
    if listen.lower() =="y":
        playsound(filename)

    Finally, let's put all the code together and execute it.

    #Python program to record an audio file.

    import sounddevice as sd
    from scipy.io.wavfile import write
    from playsound import playsound
    import time
    
    def timer(duration):
        while duration: 
            mins, secs = divmod(duration, 60) 
            timer = f"{mins} mins:{secs} seconds Left"
            print(timer, end=" \r") 
            time.sleep(1) 
            duration -= 1
    
    def record_audio(filename):
        
        #frequency
        fs=44100  #frames per second  
        duration = 10  # seconds in integer
        
        print("Recording..........")
    
        #start recording 
        myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=2)
    
        timer(duration)    #call timer function
        sd.wait()
    
        #write the data in filename and save it
        write(filename, fs, myrecording)
    
    filename ="new_record.wav"
    record_audio(filename)
    
    listen = input("Do you want to listen the recorded audio? [y/n]")
    
    if listen.lower() =="y":
        playsound(filename)

    Output

    When you execute the program, look in the directory where your Python script is located. There you will find a new wav audio file with the name new_record.wav .

    Conclusion

    In this Python tutorial, you learned " How to Play audio in Python? " and " How to Record Audio in Python? " In this tutorial, we have used three Python libraries, which are playsound , sounddevice , and Scipy .

    We would recommend you read the official documentation of these three libraries if you want to perform more audio-related functions in Python. Let us know in the comments if you come across any issues.

    People are also reading:

    Leave a Comment on this Post

    0 Comments