python获取音频时长的方法

python获取音频时长的方法,第1张

python获取音频时长的方法
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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5670351.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存