Help us understand the problem. What is going on with this article?

Pythonでmp3を読み込む

More than 1 year has passed since last update.

Pydubでmp3を読み込んでStreamにぶち込みたい

pyaudioでwav形式のやり方はよく見かけたけれど
mp3などのpydubを通したやり方が見つけられなかった
同じ境遇に会ってしまった人に捧ぐ

環境

python 3.6.4
macOs Mojave 10.14.1
PyAudio 0.2.11
pydub 0.23.0

環境作り

python -m venv ./venv
source ./venv/bin/activate

仮想環境を作ったら必要なライブラリを入れる

pip install pyaudio
pip install pydub

pythonでmp3を読み込んで再生する

app.py
from pydub import AudioSegment
from pydub.playback import play

audio_data = AudioSegment.from_mp3('./sample.mp3')
play(audio_data)

ここまでは調べたらすぐ出た
けどやりたいのは音を鳴らすのではない

pydubでstreamにぶち込む

app.py
import pyaudio
from pydub import AudioSegment
from pydub.utils import make_chunks

audio_data = AudioSegment.from_mp3('./sample.mp3')

p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(audio_data.sample_width),
                channels=audio_data.channels,
                rate=audio_data.frame_rate,
                output=True)

for chunk in make_chunks(audio_data, 500):
    stream.write(chunk._data)

stream.stop_stream()
stream.close()

p.terminate()

make_chunkはミリ秒区切りでstreamにデータを書き込むことができる

やりたかったのはこっち
同じ再生だけどpyaudioを明示的に呼び出したかった
これでリアルタイムでmp3にエフェクトかけたり、解析したりできるはず

忘れそうなので覚書

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away