There are two ways to get the duration of an mp3 file. One is to use mutagen and the other is to use pysox. Each method has its strengths and weaknesses.
The mutagen method is lighter and faster than the pysox method.
That's why mutagen only checks ID3 tags in mp3 files. On the other hand, pysox seems to use the Sox CLI to check the binaries of mp3 files.
The pysox method can determine the duration without using ID3 information, that is, it can recognize files with invalid ID3 information or files without ID3 information. By using pysox, you can check the duration without using ID3 information, that is, you can detect the duration of files with invalid ID3 information or files without ID3 information.
from mutagen.mp3 import MP3
def mutagen_length(path):
try:
audio = MP3(path)
length = audio.info.length
return length
except:
return None
length = mutagen_length(wav_path)
print("duration sec: " + str(length))
print("duration min: " + str(int(length/60)) + ':' + str(int(length%60)))
Note: pysox needs SOX cli.
import sox
def sox_length(path):
try:
length = sox.file_info.duration(path)
return length
except:
return None
length = sox_length(mp3_path)
print("duration sec: " + str(length))
print("duration min: " + str(int(length/60)) + ':' + str(int(length%60)))
Recommended Posts