18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでmp3を読み込む

Posted at

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にエフェクトかけたり、解析したりできるはず

忘れそうなので覚書

18
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?