使用 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 秒

​​

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

数据可以如此美好!

相关推荐
ZTLJQ10 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
2401_8914821710 小时前
多平台UI框架C++开发
开发语言·c++·算法
H5css�海秀10 小时前
今天是自学大模型的第一天(sanjose)
后端·python·node.js·php
阿贵---10 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
88号技师10 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t1987512810 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神10 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
m0_7269659811 小时前
面面面,面面(1)
java·开发语言
happymaker062611 小时前
web前端学习日记——DAY05(定位、浮动、视频音频播放)
前端·学习·音视频
2401_8319207411 小时前
分布式系统安全通信
开发语言·c++·算法