Table of Contents
Syntax
algorithm
Approaches
Method 1: Use wave library
Example
Output
Approach 2: Using the pydub library
Method 3 of using librosa library:
Approach 4: Using the ffmpeg-python library
结论
Home Backend Development Python Tutorial How to get the duration of audio in Python?

How to get the duration of audio in Python?

Sep 02, 2023 pm 06:53 PM
python Audio duration

How to get the duration of audio in Python?

The field of audio processing has expanded significantly in recent years, and Python has become a common choice for handling tasks surrounding audio manipulation. When working with audio, one of the common tasks is to determine the length of the audio file, which is useful in various applications such as creating playlists, audio data analysis, or developing audio editing tools.

Throughout this article, you will be guided through a variety of techniques, ranging from the basic to the advanced, in order to obtain the duration of audio using Python. Real code examples will be provided along the way. Before delving deeper into the subject matter, it is crucial to gain an understanding of the fundamental concepts and terminology that pertain to audio processing. This will give you the necessary foundation to implement the various approaches presented later in the article. Let's start with the definition of audio duration and then explore the syntax and algorithms for calculating it.

The term "audio duration" refers to the length of time an audio file plays, usually measured in seconds or minutes. This value is affected by a series of characteristics that define the audio file, including number of samples, channels, and sample rate. A thorough grasp of this knowledge is important for a variety of applications, including but not limited to transcription, analysis, and audio editing.

Syntax

Python provides a variety of libraries to manage audio file processing. These libraries include wave, pydub, and librosa, each with its own unique syntax and functions for uploading audio files and measuring their duration. The typical process for determining the duration of an audio file includes the following steps:

  • Importing the mandatory libraries.

  • Read audio files.

  • Extracting the file's characteristics (such as the sample rate, quantity of samples, and channel quantity).

  • Calculating the duration utilizing the extracted characteristics.

algorithm

To get the duration of an audio file in Python, you can implement the following algorithm -

  • Implement the appropriate library to upload the audio file.

  • Extract relevant features of audio files, including sampling rate, number of channels and number of frames.

  • Calculate the audio file's duration by dividing the number of frames by the sample rate.

  • Output the duration value by printing or returning it.

Approaches

We will now explore several techniques for determining the duration of audio files in Python. The following methods will be introduced −

  • By utilizing the wave library.

  • By using the pydub library.

  • Use librosa library.

  • By using the ffmpeg-python library.

Method 1: Use wave library

The wave library is a built-in module of Python that provides support for WAV files. Here is a complete code example demonstrating how to get the duration of an audio file using the wave library -

Example

import wave
def get_duration_wave(file_path):
   with wave.open(file_path, 'r') as audio_file:
      frame_rate = audio_file.getframerate()
      n_frames = audio_file.getnframes()
      duration = n_frames / float(frame_rate)
      return duration
file_path = 'example.wav'
duration = get_duration_wave(file_path)
print(f"Duration: {duration:.2f} seconds")
Copy after login

Output

Duration: 10.00 seconds
Copy after login
Copy after login
Copy after login
Copy after login

Approach 2: Using the pydub library

The pydub library stands as a commonly used and simple-to-utilize tool for the manipulation of audio. In order to make use of pydub, you must first install it via pip install pydub. Here's a code example to get the duration using pydub −

Example

from pydub import AudioSegment
def get_duration_pydub(file_path):
   audio_file = AudioSegment.from_file(file_path)
   duration = audio_file.duration_seconds
   return duration
file_path = 'example.wav'
duration = get_duration_pydub(file_path)
print(f"Duration: {duration:.2f} seconds")
Copy after login

Output

Duration: 10.00 seconds
Copy after login
Copy after login
Copy after login
Copy after login

Within this particular code snippet, we import the AudioSegment class, which hails from the pydub library, with the purpose of reading and making alterations to audio files. To load the audio file, we call the from_file function, and the duration_seconds attribute is employed to acquire the length of the audio file in seconds.

Method 3 of using librosa library:

Librosa stands as yet another esteemed library for the processing of audio using Python, putting its emphasis mainly on the analysis of music and sound. By typing 'pip install librosa' in your terminal or command prompt, you will be able to easily and quickly install it. Here's a code example to get the duration using librosa −

Example

import librosa
def get_duration_librosa(file_path):
   audio_data, sample_rate = librosa.load(file_path)
   duration = librosa.get_duration(y=audio_data, sr=sample_rate)
   return duration
file_path = 'example.wav'
duration = get_duration_librosa(file_path)
print(f"Duration: {duration:.2f} seconds")
Copy after login

Output

Duration: 10.00 seconds
Copy after login
Copy after login
Copy after login
Copy after login

In this example, use the librosa.load function to read the audio file and obtain the audio data and sample rate. Then, use the librosa.get_duration function to calculate the duration based on the audio data and sample rate.

Approach 4: Using the ffmpeg-python library

FFmpeg is a commonly used tool for processing audio and video on various platforms. The ffmpeg-python library acts as a Python wrapper for the FFmpeg command line interface and can be installed using pip install ffmpeg-python. The following is a sample code that demonstrates how to get the duration of an audio file using ffmpeg-python −

Example

import ffmpeg
def get_duration_ffmpeg(file_path):
   probe = ffmpeg.probe(file_path)
   stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'audio'), None)
   duration = float(stream['duration'])
   return duration
file_path = 'example.wav'
duration = get_duration_ffmpeg(file_path)
print(f"Duration: {duration:.2f} seconds")
Copy after login

Output

Duration: 10.00 seconds
Copy after login
Copy after login
Copy after login
Copy after login

在这个例子中,我们使用ffmpeg.probe函数来获取与音频文件相关的元数据。随后,我们从流列表中过滤出音频流,并从流字典中提取出'duration'字段中的持续时间。

结论

在本文中,我们深入探讨了使用wave、pydub、librosa和ffmpeg-python库在Python中获取音频文件时长的四种不同方法。每种方法都有其自身的优点和限制,库的选择取决于您个人的需求和偏好。这些代码示例旨在为您提供在Python项目中实现音频时长计算的坚实基础。

The above is the detailed content of How to get the duration of audio in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Can Python parameter annotations use strings? Can Python parameter annotations use strings? Apr 01, 2025 pm 08:39 PM

Alternative usage of Python parameter annotations In Python programming, parameter annotations are a very useful function that can help developers better understand and use functions...

How do Python scripts clear output to cursor position at a specific location? How do Python scripts clear output to cursor position at a specific location? Apr 01, 2025 pm 11:30 PM

How do Python scripts clear output to cursor position at a specific location? When writing Python scripts, it is common to clear the previous output to the cursor position...

Why can't my code get the data returned by the API? How to solve this problem? Why can't my code get the data returned by the API? How to solve this problem? Apr 01, 2025 pm 08:09 PM

Why can't my code get the data returned by the API? In programming, we often encounter the problem of returning null values ​​when API calls, which is not only confusing...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

Where to download Python .whl files under Windows? Where to download Python .whl files under Windows? Apr 01, 2025 pm 08:18 PM

Python binary library (.whl) download method explores the difficulties many Python developers encounter when installing certain libraries on Windows systems. A common solution...

See all articles