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

1

2

3

4

5

6

7

8

9

10

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

1

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

1

2

3

4

5

6

7

8

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

1

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

1

2

3

4

5

6

7

8

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

1

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

1

2

3

4

5

6

7

8

9

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

1

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles