Find the duration of a WAV file in Python

In this tutorial, we are going to learn how can we Find the duration of a WAV file in Python.  Wav is one type of audio file format similar to mp3. Wav audio file is also playable.

There are various methods available on the internet for finding the duration of wav audio files, but we are going to learn a very simple and easy technique. For this task, we are going to use one of the python libraries called Pydub.

Pydub library is used to work with audio files. Various operations can be performed by it. Using pydub we can play, cut, merge, split or edit audio files.

For doing this task first we have to install pydub to our system. You can install pydub to your system using the following command.

pip install pydub

After installing it, let’s proceed toward the next task, full code to calculate duration is given below.

from pydub import AudioSegment
#loading audio file form our system
sound = AudioSegment.from_file("/content/Music/duration2.wav")

#duration calculation function
sound.duration_seconds == (len(sound) / 1000.0)

#seconds to minutes conversion
minutes_duartion = int(sound.duration_seconds // 60)
seconds_duration = round((sound.duration_seconds % 60),3)
print(minutes_duartion,':',seconds_duration)

As you can see in the above code first we have imported AudioSegment from the pydub library. Then we are loading our .wav file in the variable named ‘sound’. For calculation of the duration of the file, we are using the duration_second() function. In which we are calculating the length of the file.

The len() function returns the value in milliseconds so we are converting it to seconds. Later on, we are converting that seconds to a particular time duration. On dividing it by 60 we get minutes and using Modulo (%) operator we get the remaining seconds.

For rounding off value we are using a round() function which takes the value of rounding as a parameter. By doing so finally we are printing our duration of the file as Minutes: Seconds format.

The output of the file is shown below.

Output

1 : 15.58

Also read: How to cut a particular portion of an MP3 file in Python

Leave a Reply

Your email address will not be published.