How to play mp3 from bytes?
13,466
Solution 1
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)
Solution 2
I saw your pygame tag, so I'll to do this in pygame. Pygame can load files from bytes with this line: sound = pygame.mixer.Sound(bytes)
or sound = pygame.mixer.Sound(buffer=bytes)
. I can't guarantee this will work with mp3 files, though, you may need to use OGG or WAV files, as bytes.
Author by
tushar
Updated on July 28, 2022Comments
-
tushar almost 2 years
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 notmp3
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
-
tushar about 7 yearsI've added a code snippet in my post. This works for
wav
butmp3
files sound corrupted. -
Rameez Ahmed Sayad over 5 yearsThanks for this option , I was struggling to get IPython Audio working
-
Fernando B almost 5 yearstried this, but getting an ffmpeg error, my question is did you have ffmpeg installed via pip or into your OS?