import ffmpeg
def get_audio_lenght(audio_file) -> float:
"""
Get the lenght of the audio stream in seconds.
:param audio_file: path to file
:return: lenght of audio stream in seconds.
"""
# depends a lot on the file format:
# ogg files: audio_stream['duration'] (as float in seconds)
# mkv files: audio_stream['tags']['DURATION'] (as timecode)
# TODO: test with more file formats and write tests!
try:
probe = ffmpeg.probe(audio_file)
audio_stream = next(
(stream for stream in probe['streams'] if stream['codec_type'] == 'audio'), None)
# check if duration is in audio_stream
if 'duration' in audio_stream:
return float(audio_stream['duration'])
# check if duration is in audio_stream['tags']
elif 'tags' in audio_stream and 'DURATION' in audio_stream['tags']:
timestamp = audio_stream['tags']['DURATION']
return float(timestamp.split(':')[0]) * 3600 + float(timestamp.split(':')[1]) * 60 + float(timestamp.split(':')[2])
except ffmpeg.Error as e:
print(e.stderr)
return 0.0
Will add this in the following days!