Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to verify an mp3 file with python

Tags:

I have to detect whether a file is a valid mp3 file. So far, I have found two solutions, including:

  1. this solution from Peter Carroll

  2. 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.

like image 844
xtluo Avatar asked Jul 03 '19 12:07

xtluo


People also ask

How do I validate an MP3 file?

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.

Can Pyaudio play MP3?

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.

What is the name of the library used to play MP3 files in Python?

playsound is the most straightforward package to use if you simply want to play a WAV or MP3 file.


1 Answers

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.

like image 187
altunyurt Avatar answered Oct 01 '22 22:10

altunyurt