Home > Backend Development > Python Tutorial > How to get the duration of audio in Python?

How to get the duration of audio in Python?

WBOY
Release: 2023-09-02 18:53:05
forward
1324 people have browsed it

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!

Related labels:
source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template