使用 pydub 的 AudioSegment 获取音频时长 - python 实现

通过使用 pydub 的 AudioSegment 获取音频时长,音频常用格式如 m4a,wav等。

安装 python 库:

python 复制代码
 pip install pydub

获取 m4a 格式的音频时长代码如下,代码如下:

python 复制代码
#-*-coding:utf-8-*-
# date:2024-10
# Author: DataBall - XIAN
# Function: 获取音频时长

from pydub import AudioSegment

file_ = "test.m4a"
audio_type = "m4a"

print("音频路径:{}".format(file_))
print("音频类型:{}".format(audio_type))

audio = AudioSegment.from_file(file_, format=audio_type)

duration_ms = len(audio) # 时长毫秒
duration_seconds = duration_ms / 1000.0 # 转换为秒

print("音频时长: {:.2f} 小时, {:.2f} 分钟, {:.2f} 秒".format(duration_seconds/3600,duration_seconds/60,duration_seconds))

执行程序的log如下:

python 复制代码
音频路径:test.m4a
音频类型:m4a
音频时长: 0.15 小时, 9.14 分钟, 548.59 秒

获取 wav 格式的音频时长代码如下,代码如下:

python 复制代码
#-*-coding:utf-8-*-
# date:2024-10
# Author: DataBall - XIAN
# Function: 获取音频时长

from pydub import AudioSegment

file_ = "test.wav"
audio_type = "wav"

print("音频路径:{}".format(file_))
print("音频类型:{}".format(audio_type))

audio = AudioSegment.from_file(file_, format=audio_type)

duration_ms = len(audio) # 时长毫秒
duration_seconds = duration_ms / 1000.0 # 转换为秒

print("音频时长: {:.2f} 小时, {:.2f} 分钟, {:.2f} 秒".format(duration_seconds/3600,duration_seconds/60,duration_seconds))

执行程序的log如下:

python 复制代码
音频路径:test.wav
音频类型:wav
音频时长: 0.00 小时, 0.04 分钟, 2.49 秒

​​

助力快速掌握数据集的信息和使用方式。

数据可以如此美好!

相关推荐
zone773916 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant16 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来17 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_17 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend18 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽18 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_2 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮2 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling2 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python