I have to detect whether a file is a valid mp3 file. So far, I have found two solutions, including:
this solution from Peter Carroll
using try-catch
expression:
try:
_ = librosa.get_duration(filename=mp3_file_path)
return True
except:
return False
Both solutions above work, but may have some drawbacks, the 1st solution seems too complicated while the 2nd solution is too slow(in seconds depending on the length of the audio). So I wonder whether there is a better way to verify an mp3 file with python?
Thanks.
To check a single MP3 file, highlight it by left-clicking on it. Click the File menu tab at the top of the screen and choose the Scan option. You can also right-click a single file and choose Scan from the pop-up menu.
Pyaudio allows us to play and record sounds with Python. To play MP3, however, we first need to convert the MP3 file to WAV format with ffmpeg. To use ffmpeg in Python, we use an interface tool called Pydub, which directly calls our ffmpeg executable and integrates with Pyaudio.
playsound is the most straightforward package to use if you simply want to play a WAV or MP3 file.
Try eyed3.
In [8]: %timeit eyed3.load("some.mp3").info.time_secs
1.94 ms ± 43.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [10]: %timeit eyed3.load("120mb_video.mp4")
4.43 ms ± 26.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Basically, if eyed3.load returns None, the file is not a valid mp3 file. And it runs in 4.5 ms at average for even a 120mb file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With