Read MP3 in Python 3

65,758

Solution 1

I ended up using an mpg123 subprocess to convert the mp3 to wav, and then I use scipy.io.wavfile.read to read the wav file.

Solution 2

You could use librosa:

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

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

Solution 3

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.

Solution 4

Can be done with pydub:

import array
from pydub import AudioSegment
from pydub.utils import get_array_type

sound = AudioSegment.from_file(file=path_to_file)
left = sound.split_to_mono()[0]

bit_depth = left.sample_width * 8
array_type = get_array_type(bit_depth)

numeric_array = array.array(array_type, left._data)

Solution 5

I am considering using FFmpeg as a subprocess. There is a Python wrapper called pyffmpeg, but I had difficulty installing it on my system (OS X 10.7.3).

You may also want to look at the code here for calling FFmpeg as a subprocess from Python: https://github.com/albertz/learn-midi/blob/master/decode.py

Share:
65,758
Andreas Jansson
Author by

Andreas Jansson

Updated on January 08, 2021

Comments

  • Andreas Jansson
    Andreas Jansson over 3 years

    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.