'''
pymediainfo: pip3 install pymediainfo 版本:5.1.0
不支持网络音频
'''
class pymediainfoTest():
@classmethod
def getAudioTimes(cls, audio_path):
__lib_pymediainfo = __import__('pymediainfo', fromlist=['MediaInfo'])
media_info = __lib_pymediainfo.MediaInfo.parse(audio_path)
data = json.loads(media_info.to_json())
# 多声道
duration = data['tracks'][0]['duration']
duration1 = data['tracks'][1]['duration']
print(duration, data['tracks'][0]['other_duration'])
print(duration1, data['tracks'][1]['other_duration'])
# pymediainfoTest.getAudioTimes(music_url)
'''
mutagen: pip3 install mutagen 版本:1.45.1
不支持网络音频
'''
class MutagenTest():
@classmethod
def getAudioTimes(cls, audio_path):
__lib_mutagen = __import__('mutagen', fromlist=['mp3'])
audio = __lib_mutagen.mp3.MP3(audio_path)
mp3_times = int(audio.info.length)
f = int(mp3_times/60)
m = mp3_times - f * 60
print('%s秒, %s分%s秒' % (mp3_times, f, m))
# MutagenTest.getAudioTimes()
'''
librosa: pip3 install librosa 版本:0.9.1 http://librosa.org/doc/latest/index.html
不支持网络音频
错误: audioread.exceptions.NoBackendError
解决:找到ffdec.py文件(python/lib/site-packages/audioread/ffdec.py),打开找到COMMANDS = (‘ffmpeg’, ‘avconv’)这行,将’ffmpeg’修改成你的ffmpeg.exe的路径(建议路径引号前面加上r)。
速度慢
'''
class LibrosaTest():
__slots__ = ()
# 取音频时长
@classmethod
def getAudioTimes(cls, audio_path):
__lib_librosa = __import__('librosa')
duration = __lib_librosa.get_duration(filename=audio_path)
print(duration)
# LibrosaTest.getAudioTimes()
'''
pydub: pip3 install pydub 版本:0.25.1 https://github.com/jiaaro/pydub
需要下载ffmpeg:
https://ffmpeg.org/-->download-->windows builds by BtbN-->ffmpeg-master-latest-win64-gpl.zip(104M)
解压后将/bin添加到系统环境变量path中,重启vscode才会生效
'''
class PydubTest():
__lib_pydub = __import__('pydub')
# 方法一,支持网络音频
@classmethod
def getAudioTimes(cls):
song = cls.__lib_pydub.utils.mediainfo(music_url)
print(song['duration'])
# 方法二,不支持网络音频
@classmethod
def getAudioTimes1(cls):
sound = cls.__lib_pydub.AudioSegment.from_mp3(music_url)
#获取文件时长
print(sound.duration_seconds)
# PydubTest.getAudioTimes1()
'''
ffprobe: 下载ffmpeg 版本:5.0
通过命令行调用,支持网络音频
'''
class FfprobeTest():
@classmethod
def getAudioTimes(cls, audio_path):
__lib_subprocess = __import__('subprocess')
__lib_json = __import__('json')
# 没有添加系统环境变量,也可以指定ffprobe的路径
command = "ffprobe -loglevel quiet -print_format json -show_format -show_streams -i %s" % (audio_path)
result = __lib_subprocess.Popen(command, shell=True, stdout=__lib_subprocess.PIPE, stderr=__lib_subprocess.STDOUT)
out = result.stdout.read()
temp = str(out.decode('utf-8'))
info = __lib_json.loads(temp)
print(info['streams'][0]['duration'])
FfprobeTest.getAudioTimes(music_url)
|