import librosa
import wave
import contextlib
import eyed3
from pydub import AudioSegment
def get_duration_mp3(file_path):
""" 获取mp3音频文件时长 :param file_path: :return: """
mp3Info = eyed3.load(file_path)
return mp3Info.info.time_secs
def get_duration_wav(file_path):
""" 获取wav音频文件时长 :param file_path: :return: """
with contextlib.closing(wave.open(file_path, 'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
return duration
def get_duration_mp3_and_wav(file_path):
""" 获取mp3/wav音频文件时长 :param file_path: :return: """
duration = librosa.get_duration(filename=file_path)
return duration
# 获取wav音频时长的又一种方式
def get_wav_make(file_path):
sound = AudioSegment.from_wav(file_path)
duration = sound.duration_seconds # 音频时长(ms)
return duration
if __name__ == "__main__":
file_path = './xxx.mp3'
# file_path = './task_8b1DA380f9E7.wav'
# 仅mp3
# duration = get_duration_mp3(file_path)
# 仅wav
# duration = get_duration_wav(file_path)
# mp3 和 wav 均可
duration = get_duration_mp3_and_wav(file_path)
print(f'duration = { duration}')
参考:
https://juejin.cn/post/6979432109580484639