Last modified: Apr 16, 2026 By Alexander Williams
Get Audio File Length in Python
Working with audio files is a common task. You often need to know their duration. Python makes this easy with several libraries.
This guide shows you how to find audio length. We will use popular tools like pydub, librosa, and the built-in wave module.
You will learn the best method for your project. This is a key skill in Python audio processing.
Why You Need Audio File Duration
Knowing an audio file's length is useful. It helps in editing, analysis, and playback control.
You might need it to trim files, calculate bitrates, or display progress bars. It's a fundamental step in any audio workflow.
Python provides simple ways to extract this metadata. You don't need complex software.
Method 1: Using the Pydub Library
Pydub is a powerful, user-friendly library. It can handle many audio formats with ease.
First, you must install it. Use the pip package manager in your terminal.
pip install pydub
You also need ffmpeg installed on your system. Pydub uses it to read MP3 and other formats. After installation, you can load and measure audio.
from pydub import AudioSegment
# Load the audio file
audio = AudioSegment.from_file("sample_song.mp3", format="mp3")
# Get the length in milliseconds
duration_ms = len(audio)
# Convert to seconds
duration_sec = duration_ms / 1000
print(f"Audio length: {duration_ms} ms")
print(f"Audio length: {duration_sec:.2f} seconds")
Audio length: 185000 ms
Audio length: 185.00 seconds
The len() function returns the length in milliseconds. Pydub is great for quick tasks. It supports MP3, WAV, FLAC, and more.
Method 2: Using the Librosa Library
Librosa is the go-to library for audio analysis. It is perfect for music information retrieval tasks.
Install it using pip. It has many dependencies for numerical computing.
pip install librosa
Librosa loads audio as a NumPy array. It also gives you the sample rate. You can calculate duration from these.
import librosa
# Load audio file. Returns audio array (y) and sample rate (sr)
y, sr = librosa.load("sample_song.wav")
# Calculate duration in seconds
duration = librosa.get_duration(y=y, sr=sr)
# Alternative: Use the length of the array
duration_alt = len(y) / sr
print(f"Sample Rate: {sr} Hz")
print(f"Duration (librosa function): {duration:.2f} seconds")
print(f"Duration (calculated): {duration_alt:.2f} seconds")
Sample Rate: 22050 Hz
Duration (librosa function): 185.02 seconds
Duration (calculated): 185.02 seconds
The librosa.get_duration() function is the simplest way. Librosa is ideal for in-depth audio analysis and machine learning.
Method 3: Using the Built-in Wave Module
Python has a built-in module for WAV files. It's called wave. It's lightweight and requires no installation.
It only works with standard WAV files. It won't open MP3 or other compressed formats.
import wave
# Open the WAV file in read mode
with wave.open("sample_sound.wav", 'rb') as wav_file:
# Get the number of frames
n_frames = wav_file.getnframes()
# Get the frame rate (samples per second)
framerate = wav_file.getframerate()
# Calculate duration
duration = n_frames / float(framerate)
print(f"Number of frames: {n_frames}")
print(f"Frame rate: {framerate} Hz")
print(f"Audio duration: {duration:.2f} seconds")
Number of frames: 4077568
Frame rate: 22050 Hz
Audio duration: 185.00 seconds
You use getnframes() and getframerate() for the calculation. This method is fast and perfect for simple WAV file tasks.
Choosing the Right Method
How do you pick the best library? It depends on your file format and project goals.
Use Pydub for simplicity and multi-format support. It's excellent for basic editing and quick scripts.
Use Librosa for advanced audio analysis. If you plan to extract features or work with machine learning, start here.
Use the wave module for standard WAV files. It's perfect when you want no external dependencies.
For a broader look at tools, see our guide on Python audio libraries.
Handling Errors and Exceptions
Your code should handle problems gracefully. Files might be missing or corrupted.
Always use try-except blocks. This makes your program robust and user-friendly.
from pydub import AudioSegment
import os
file_path = "my_audio.mp3"
try:
if not os.path.exists(file_path):
raise FileNotFoundError(f"The file {file_path} was not found.")
audio = AudioSegment.from_file(file_path, format="mp3")
duration_sec = len(audio) / 1000
print(f"Success! Audio is {duration_sec:.2f} seconds long.")
except FileNotFoundError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
This checks if the file exists first. It catches specific errors for better feedback.
Conclusion
Getting an audio file's length in Python is straightforward. You have multiple reliable options.
Use Pydub for general-purpose tasks with many formats. Choose Librosa for scientific analysis and machine learning. The wave module is best for simple WAV file handling without extra installs.
Remember to handle errors and choose the right tool for your job. This skill is a cornerstone of effective audio processing in Python.
Start experimenting with these code examples on your own audio files today.