如何从字节播放 mp3? [英] How to play mp3 from bytes?

查看:97
本文介绍了如何从字节播放 mp3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法直接使用python从字节播放mp3?如果没有,我可以将二进制文件转换为不同的音频格式并使二进制文件可播放吗?

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?

以下代码适用于 wav 文件但不适用于 mp3

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)

问题已解决,如果您遇到类似问题,请参阅下面我的回答

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

推荐答案

对于任何可能面临类似问题的人来说,这是可行的

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)

这篇关于如何从字节播放 mp3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆