目录
Syntax
算法
Approaches
方法一:使用wave库
Example
Output
Approach 2: Using the pydub library
使用librosa库的方法三:
Approach 4: Using the ffmpeg-python library
结论
首页 后端开发 Python教程 如何在Python中获取音频的持续时间?

如何在Python中获取音频的持续时间?

Sep 02, 2023 pm 06:53 PM
python 音频 持续时间

如何在Python中获取音频的持续时间?

近年来,音频处理领域取得了显着的扩展,Python已成为处理围绕音频操作的任务的常见选择。在处理音频时,常见的任务之一是确定音频文件的长度,这在各种应用中都非常有用,例如创建播放列表、音频数据分析或开发音频编辑工具。

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.

“音频时长”一词指的是音频文件播放的时间长度,通常以秒或分钟为单位进行测量。这个值受到一系列定义音频文件的特征的影响,包括样本数量、声道和采样率。对这些知识的全面掌握对于各种应用非常重要,包括但不限于转录、分析和音频编辑。

Syntax

Python提供了各种各样的库来管理音频文件处理。这些库包括wave、pydub和librosa,每个库都有自己独特的语法和函数,用于上传音频文件和测量它们的时间长度。确定音频文件持续时间的典型过程包括以下步骤:

  • Importing the mandatory libraries.

  • 读取音频文件。

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

  • Calculating the duration utilizing the extracted characteristics.

算法

要在Python中获取音频文件的持续时间,可以实现以下算法 -

  • Implement the appropriate library to upload the audio file.

  • 提取音频文件的相关特征,包括采样率、通道数量和帧数。

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

  • 通过打印或返回它来输出持续时间值。

Approaches

我们现在将探讨在Python中确定音频文件持续时间的几种技术。将介绍以下方法 −

  • 通过利用波浪库。

  • By using the pydub library.

  • 使用librosa库。

  • By using the ffmpeg-python library.

方法一:使用wave库

波浪库是Python的内置模块,提供对WAV文件的支持。这是一个完整的代码示例,演示如何使用波浪库获取音频文件的持续时间 -

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")
登录后复制

Output

Duration: 10.00 seconds
登录后复制
登录后复制
登录后复制
登录后复制

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")
登录后复制

Output

Duration: 10.00 seconds
登录后复制
登录后复制
登录后复制
登录后复制

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.

使用librosa库的方法三:

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")
登录后复制

Output

Duration: 10.00 seconds
登录后复制
登录后复制
登录后复制
登录后复制

在这个例子中,使用librosa.load函数来读取音频文件并获取音频数据和采样率。然后,利用librosa.get_duration函数基于音频数据和采样率来计算持续时间。

Approach 4: Using the ffmpeg-python library

FFmpeg是在各种平台上常用的用于处理音频和视频的工具。 ffmpeg-python库充当了FFmpeg命令行界面的Python包装器,并可以使用pip install ffmpeg-python进行安装。以下是一个示例代码,演示了如何使用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")
登录后复制

Output

Duration: 10.00 seconds
登录后复制
登录后复制
登录后复制
登录后复制

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

结论

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

以上是如何在Python中获取音频的持续时间?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

2小时的Python计划:一种现实的方法 2小时的Python计划:一种现实的方法 Apr 11, 2025 am 12:04 AM

2小时内可以学会Python的基本编程概念和技能。1.学习变量和数据类型,2.掌握控制流(条件语句和循环),3.理解函数的定义和使用,4.通过简单示例和代码片段快速上手Python编程。

Python:探索其主要应用程序 Python:探索其主要应用程序 Apr 10, 2025 am 09:41 AM

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

Navicat查看MongoDB数据库密码的方法 Navicat查看MongoDB数据库密码的方法 Apr 08, 2025 pm 09:39 PM

直接通过 Navicat 查看 MongoDB 密码是不可能的,因为它以哈希值形式存储。取回丢失密码的方法:1. 重置密码;2. 检查配置文件(可能包含哈希值);3. 检查代码(可能硬编码密码)。

如何将 AWS Glue 爬网程序与 Amazon Athena 结合使用 如何将 AWS Glue 爬网程序与 Amazon Athena 结合使用 Apr 09, 2025 pm 03:09 PM

作为数据专业人员,您需要处理来自各种来源的大量数据。这可能会给数据管理和分析带来挑战。幸运的是,两项 AWS 服务可以提供帮助:AWS Glue 和 Amazon Athena。

redis怎么读取队列 redis怎么读取队列 Apr 10, 2025 pm 10:12 PM

要从 Redis 读取队列,需要获取队列名称、使用 LPOP 命令读取元素,并处理空队列。具体步骤如下:获取队列名称:以 "queue:" 前缀命名,如 "queue:my-queue"。使用 LPOP 命令:从队列头部弹出元素并返回其值,如 LPOP queue:my-queue。处理空队列:如果队列为空,LPOP 返回 nil,可先检查队列是否存在再读取元素。

Redis如何查看服务器版本 Redis如何查看服务器版本 Apr 10, 2025 pm 01:27 PM

问题:如何查看 Redis 服务器版本?使用命令行工具 redis-cli --version 查看已连接服务器的版本。使用 INFO server 命令查看服务器内部版本,需解析返回信息。在集群环境下,检查每个节点的版本一致性,可使用脚本自动化检查。使用脚本自动化查看版本,例如用 Python 脚本连接并打印版本信息。

redis怎么启动服务器 redis怎么启动服务器 Apr 10, 2025 pm 08:12 PM

启动 Redis 服务器的步骤包括:根据操作系统安装 Redis。通过 redis-server(Linux/macOS)或 redis-server.exe(Windows)启动 Redis 服务。使用 redis-cli ping(Linux/macOS)或 redis-cli.exe ping(Windows)命令检查服务状态。使用 Redis 客户端,如 redis-cli、Python 或 Node.js,访问服务器。

Navicat的密码安全性如何? Navicat的密码安全性如何? Apr 08, 2025 pm 09:24 PM

Navicat的密码安全性依赖于对称加密、密码强度和安全措施的结合。具体措施包括:采用SSL连接(前提是数据库服务器支持并正确配置证书)、定期更新Navicat、使用更安全的方式(如SSH隧道)、限制访问权限,最重要的是,绝不记录密码。

See all articles