How to play mp3 from bytes?

tushar picture tushar · May 12, 2017 · Viewed 10k times · Source

Is there a way to play mp3 from bytes directly using python? If not, can I convert the binary to a different audio format and make the binary playable?

Edit: The following code works for wav files but not mp3

from pygame import mixer, time

mixer.pre_init(44100, -16, 2, 2048)
mixer.init()

data = open('filename.mp3', 'rb').read()
sound = mixer.Sound(buffer=data)

audio = sound.play()
while audio.get_busy():
    time.Clock().tick(10)

Edit: The problem has been solved, see my answer below if you're facing a similar issue

Answer

tushar picture tushar · May 13, 2017

For anyone who might be facing a similar problem, this works

from pydub import AudioSegment
from pydub.playback import play
import io

data = open('filename.mp3', 'rb').read()

song = AudioSegment.from_file(io.BytesIO(data), format="mp3")
play(song)