How to get the duration of audio in Python?
Last Updated : 24 Feb, 2021
It is possible to find the duration of the audio files using Python language which is rich in the use of its libraries. The use of some libraries like mutagen, wave, audioread, etc. is not only limited to extract the length/duration of the audio files but comes with much more functionality.
Source Audio File:
Now let us see, how we can get the duration of any audio file using python:
Method 1: Using the Python Library 'Mutagen'
Mutagen is a Python module to handle audio metadata. It supports various formats of audio files like wavpack, mp3, Ogg, etc. Below are the steps to use it for computing the duration of the audio files:
Step 1: Install Mutagen
Since Mutagen is an external python library, hence first it needs to be installed using the pip command as follows:
pip install mutagen
Step 2: Import Mutagen
Once installed, its need to be imported into our script using the following command,
import mutagen
In our program, we are going to use some inbuilt functions of the Mutagen library, Let's explore them a bit to get a better understanding of the Source Code:
1) WAVE()
Syntax: WAVE(file thing/filename)
Use: It simply creates a WAVE object of the filename being provided as a parameter.
Example: voice = WAVE("sample.wav")
2) info
Syntax: variable.info
Use: It fetches the metadata of the audio file whose WAVE object has been created.
Example: voice_info = voice.info
3) length
Syntax: variable.length
Use: It returns audio length in seconds. The value returned is in float(by default).
Example: voice_length = voice_info.length
Below is the actual Python Script that records the duration/length of any audio file:
Python3 import mutagen from mutagen.wave import WAVE # function to convert the information into # some readable format def audio_duration(length): hours = length // 3600 # calculate in hours length %= 3600 mins = length // 60 # calculate in minutes length %= 60 seconds = length # calculate in seconds return hours, mins, seconds # returns the duration # Create a WAVE object # Specify the directory address of your wavpack file # "alarm.wav" is the name of the audiofile audio = WAVE("alarm.wav") # contains all the metadata about the wavpack file audio_info = audio.info length = int(audio_info.length) hours, mins, seconds = audio_duration(length) print('Total Duration: {}:{}:{}'.format(hours, mins, seconds))
Output:
Total Duration: 0:0:2
Method 2: Using the Python Library 'Audioread'
Audioread is cross-library audio decoding for Python. It decodes audio files using whichever backend is available. Below are the steps to use it for computing the duration of the audio files:
Step 1: Install audioread
Since audioread is an external python library, hence first it needs to be installed using the pip command as follows:
pip install audioread
Step 2: Import audioread
Once installed, its need to be imported into our script using the following command,
import audioread
In our program, we are going to use some inbuilt functions of audioread library, Let's explore them a bit to get a better understanding of the Source Code:
1) audio_open()
Syntax: audioread.audio_open(filename)
Use: It simply opens an audio file using a library available on the system
Example: with audioread.audio_open('example.wav') as ex:
#statement 1...statement n
2) duration
Syntax: fileobject.duration
Use: It returns the length of the audio in seconds (a float by default).
Example: variable= fptr.duration
Below is the actual Python Script that records the duration/length of any audio file:
Python3 # METHOD 2 import audioread # function to convert the information into # some readable format def duration_detector(length): hours = length // 3600 # calculate in hours length %= 3600 mins = length // 60 # calculate in minutes length %= 60 seconds = length # calculate in seconds return hours, mins, seconds # alarm.wav is the name of the audio file # f is the fileobject being created with audioread.audio_open('alarm.wav') as f: # totalsec contains the length in float totalsec = f.duration hours, mins, seconds = duration_detector(int(totalsec)) print('Total Duration: {}:{}:{}'.format(hours, mins, seconds))
Output:
Total Duration: 0:0:2
Method 3: Using the Python Library 'Scipy'
SciPy has many modules, classes, and functions available to read data from and write data to a variety of file formats like Wav sound files, MATLAB files, etc. Below are the steps to use it for computing the duration of the audio files:
Step 1: Install Scipy
Since Scipy is an external python library, hence first it needs to be installed using the pip command as follows:
pip install scipy
Step 2: Import Scipy
Once installed, its need to be imported into our script using the following command,
import scipy from scipy.io import wavfile
In our program, we are going to use some inbuilt functions of the Scipy library, Let's explore them a bit to get a better understanding of the Source Code:
1) scipy.io.wavfile.read()
Syntax: scipy.io.wavfile.read(filename)
Use: It returns the sample rate (in samples/sec) and data from a WAV file. The file can be an open file or a filename. The returned sample rate is a Python integer. The data is returned as a NumPy array with a data-type determined from the file.
Example: variable1,variable2 = scipy.io.wavfile.read('example.wav')
Below is the actual Python Script that records the duration/length of any audio file:
Python3 # Method 3 import scipy from scipy.io import wavfile # function to convert the information into # some readable format def output_duration(length): hours = length // 3600 # calculate in hours length %= 3600 mins = length // 60 # calculate in minutes length %= 60 seconds = length # calculate in seconds return hours, mins, seconds # sample_rate holds the sample rate of the wav file # in (sample/sec) format # data is the numpy array that consists # of actual data read from the wav file sample_rate, data = wavfile.read('alarm.wav') len_data = len(data) # holds length of the numpy array t = len_data / sample_rate # returns duration but in floats hours, mins, seconds = output_duration(int(t)) print('Total Duration: {}:{}:{}'.format(hours, mins, seconds))
Output:
Total Duration: 0:0:2
Similar Reads
Pafy - Getting Duration of the video
In this article we will see how we can get the duration of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Duration of the video is the time period of the
2 min read
Find the Duration of Gif Image in Python
Python can perform various image processing tasks, including analyzing GIF images to determine their total duration. By utilizing libraries such as PIL (Pillow) and Imageio, we can easily read GIF files and calculate their durations by summing the frame durations. In this article, we will learn to f
3 min read
How to Play and Record Audio in Python?
As python can mostly do everything one can imagine including playing and recording audio. This article will make you familiar with some python libraries and straight-forwards methods using those libraries for playing and recording sound in python, with some more functionalities in exchange for few e
10 min read
How does the Python Interpreter check thread duration?
In Python, threads are a means of achieving concurrent execution. The Python interpreter employs a mechanism to manage and monitor the duration and execution of threads. Understanding how the Python interpreter handles thread duration is essential for developing efficient and responsive multithreade
3 min read
Get video duration using Python - OpenCV
OpenCV is one of the most popular cross-platform libraries and it is widely used in Deep Learning, image processing, video capturing, and many more. In this article, we will learn how to get the duration of a given video using python and computer vision. Prerequisites: Opencv moduledatetime module
1 min read
Pafy - Getting Best Audio Stream of the Video
In this article we will see how we can get best audio stream of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Best audio stream is basically a audio stre
2 min read
Pafy - Getting Description of the Video
In this article we will see how we can get the description of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. A YouTube video description is the text below
2 min read
Python VLC MediaPlayer - Getting Audio Tracks Description
In this article we will see how we can get the audio tracks description of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the b
2 min read
How to check the execution time of Python script ?
In this article, we will discuss how to check the execution time of a Python script. There are many Python modules like time, timeit and datetime module in Python which can store the time at which a particular section of the program is being executed. By manipulating or getting the difference betwee
6 min read
Pafy - Getting Audio Streams of the Video
In this article we will see how we can get the audio streams of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Audio streams are basically all the availab
2 min read