Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Get video duration using Python - OpenCV
Next article icon

How to get the duration of audio in Python?

Last Updated : 24 Feb, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Next Article
Get video duration using Python - OpenCV

T

tanyagarg3434
Improve
Article Tags :
  • Python
  • python-utility
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences