Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read MP3 in Python 3

What I want to do is simply

mp3 = read_mp3(mp3_filename) audio_left = mp3.audio_channels[0] 

where audio_left will contain raw PCM audio data.

I was looking at Play a Sound with Python, but most of the suggested modules are not ported to Python 3 yet. If possible I'd like to avoid having to install a fully-fledged game dev library.

I'm a complete Python beginner, so I'd like to start off using Python 3.

like image 395
Andreas Jansson Avatar asked Feb 26 '12 23:02

Andreas Jansson


People also ask

Can Python read mp3 files?

Conclusion: Playing and Recording Sound in Python You are now able to: Play a large range of audio formats, including WAV, MP3 and NumPy arrays. Record audio from your microphone to a NumPy or Python array.

How do I read an audio file in Python?

open() This function opens a file to read/write audio data. The function needs two parameters - first the file name and second the mode. The mode can be 'wb' for writing audio data or 'rb' for reading.

How do I read an mp3 file?

All you have to do is double-click on the MP3 file you want to listen to and by default, your audio player will open the file and start playing. If, however, you prefer a different audio player than either of those, changing the association of a file is a simple process on either Windows or macOS.


2 Answers

You could use librosa:

import librosa y, sr = librosa.load('your_file.mp3') 

Further information: https://github.com/librosa/librosa

like image 82
Nir Avatar answered Oct 16 '22 20:10

Nir


To make it easier I'd convert with some tools mp3 to wav, either:

$ ffmpeg -i foo.mp3 -vn -acodec pcm_s16le -ac 1 -ar 44100 -f wav foo.wav or $ mpg123 -w foo.wav foo.mp3 

Then read the WAV with one of the python WAV libraries. I'd recommend PySoundFile because it works with most generated WAV correctly and installed without issue (as opposed to scikits.audiolab).

Note: Even though scipy.io.wavfile.read() gave me a "WavFileWarning: Unfamiliar format bytes" warning, it also loaded the file properly.

like image 28
Wernight Avatar answered Oct 16 '22 20:10

Wernight