Read Audio File With Python wave Module

Python program is famous for the number of modules they provide. Some people mock this amazing language and underestimate the power of using this beautiful module that python programming provides to us. While some of us enjoy using these built-in and third-party python packages.

Python wave module is used to work with the WAV sound format. Though the python wave module does not support the compression and decompression of the WAV files still it is helpful in mono/stereo. If you are looking for the compression of files with Python, you can have a look on here.

What is a WAV File?

WAV stands for Waveform File Format and this is a file format used as a standard for the audio file format. It is developed by IBM and Microsoft collectively. WAV file has better quality than the MP3 file format.

Before going to the FAQ about the wave module, let’s see a few examples of the wave file. We will see the different methods available in the python wave module, which can help us read and write the audio file.

How to Play audio files with Python?

To open an audio file with Python we can use the wave.open(fname) method. We can open the WAV audio file with the help of the open() method available in the wave module. wave is a built-in Python module and we do not need to install it separately.

Example No 1 : Play Audio Files

This Example uses pyauido module, if you do not know about the pyaudio module in Python, please check out it here. In this example, we will see how we can create a function that can make use of the wave.open() method to play a WAV audio file. Below is a Simple callback function to play a wave file. By default, it plays a Ding sound which is a constant in the wave module.

See the following code Example

import wave
import time
import pyaudio


def play_audio_file(fname=wave.DETECT_DING):
    """
    :param str fname: wave file name
    :return: None
    """
    ding_wav = wave.open(fname, 'rb')
    ding_data = ding_wav.readframes(ding_wav.getnframes())
    audio = pyaudio.PyAudio()
    stream_out = audio.open(
        format=audio.get_format_from_width(ding_wav.getsampwidth()),
        channels=ding_wav.getnchannels(),
        rate=ding_wav.getframerate(), input=False, output=True)
    stream_out.start_stream()
    stream_out.write(ding_data)
    time.sleep(0.2)
    stream_out.stop_stream()
    stream_out.close()
    audio.terminate() 

Load an Audio file in chunks with Python

We can use the following function that can help us load the audio file not all at once, but rather in chunk of bytes and then play it. We first create the audio object, we open the stream, we then read the data based on the chunk size we start playing it.

See the following code Example

import wave
import pyaudio
def play_wav(fname, chunk=CHUNK):
    # create an audio object
    wf = wave.open(fname, 'rb')
    p = pyaudio.PyAudio()

    # open stream based on the wave object which has been input.
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)

    # read data (based on the chunk size)
    data = wf.readframes(chunk)

    # play stream (looping from beginning of file to the end)
    while len(data) > 0:
        # writing to the stream is what *actually* plays the sound.
        stream.write(data)
        data = wf.readframes(chunk)

    # cleanup stuff
    stream.close()
    p.terminate()

How to Play Audio file from Network with Python?

To receive an audio file from the network and then play it, we can use the about play_wav() function to do so. We first read the data in chunks and then create objects of it, once the objects are created we then write them locally and play them. check out the above code.

How to Play a WAV file with Python?

If the file is located in a local disk then it is much easier for us. To read a WAV file with Python, use the wave.open() method. The wave module is only used for reading the WAV file and the pyaudio is used to actually play the file.

We need to use both the modules, the pyauido module for playing the WAV file and the python wave module to read the WAV file.

Python Example No 2: See the following code Example

import wave
import pyaudio
def play_file(fname):
    # create an audio object
    wf = wave.open(fname, 'rb')
    p = pyaudio.PyAudio()
    chunk = 1024

    # open stream based on the wave object which has been input.
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)

    # read data (based on the chunk size)
    data = wf.readframes(chunk)

    # play stream (looping from beginning of file to the end)
    while len(data) > 0:
        # writing to the stream is what *actually* plays the sound.
        stream.write(data)
        data = wf.readframes(chunk)

        # cleanup stuff.
    stream.close()
    p.terminate()

How to find the length of the audio file with Python?

The python wave module has methods that can help us find the length of an audio file if we do a few calculations. To find the length of an audio file we first have to divide the number of frames by the frame rate. We will get the total duration of the audio file. See the following example where we find the duration of an audio file.

Python Example No 3:See the following Code Example

def audio_length():
    wav_file = wave.open(f"filepath.wav", 'r')
    frames = wav_file.getnframes()
    rate = wav_file.getframerate()
    duration = frames / float(rate)
    wav_file.close()
    return duration

How to find the duration of any sound file?

The use case of the wave file is that we can find the duration or length of any sound file. To find the duration we have to need two things, frame rate and a number of frames. We then divide the number of frames by the frame rate. See the following example.

Python Example No 4:See the following code Example

def getSoundFileDuration(fn):
    '''
    Returns the duration of a wav file (in seconds)
    '''
    audiofile = wave.open(fn, "r")
    
    params = audiofile.getparams()
    framerate = params[2]
    nframes = params[3]
    
    duration = float(nframes) / framerate
    return duration 

How to find if a .wav file is valid or not?

To find the validity of a .wav audio file we need the frame rate and channels then we do the following calculations to find if the .wav file is valid or not. see the following example.Python Example No 5:
 See the following code Example

def is_valid_wav(filename):
    # check the sampling rate and number bits of the WAV
    try:
        wav_file = wave.Wave_read(filename)
    except:
        return False
    if wav_file.getframerate() != 16000 or wav_file.getsampwidth() != 2 or wav_file.getnchannels() != 1 \
        or wav_file.getcomptype() != 'NONE':
        return False
    return True

Summary and Conclusion

In this article, we have seen how we can work with sound files. the Python wave module is explored very well. If you still have any questions please let me know in the comment section. or email me at haxratali0@gmail.com with your contact information.

Leave a Comment

Scroll to Top