pydubを使って音楽を鳴らす - Python
Pythonで音楽(mp3)を鳴らすにはpydubというライブラリを使えば実現できる。
音楽鳴らすまでに行ったことはここに書いてある
音を鳴らす · Issue #2 · tamago324/CasNewCommentNoticePy
環境
$ sw_vers ProductName: Mac OS X ProductVersion: 10.13.3 BuildVersion: 17D102
音楽を鳴らすまでの手順
- ffmpegをインストール
pipenv install pydub
でpydubのインストール
pydubを使うにはffmegというソフトをインストールしなくてはいけない。これに少し手こずった
1.ffmpegをインストール
/usr/local/share/man/man3
の権限を実行するユーザーにする必要がある
$ cd /usr/local/share/man/ $ sudo chown -R $USER man3
次にffmpegをインストールする
$ brew install ffmpeg --with-libvorbis --with-sdl2 --with-theora
インストールできたか確認
$ ffmpeg ffmpeg version 4.0 Copyright (c) 2000-2018 the FFmpeg developers built with Apple LLVM version 9.0.0 (clang-900.0.39.2) configuration: --prefix=/usr/local/Cellar/ffmpeg/4.0 --enable-shared --enable-pthreads --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-gpl --enable-ffplay --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libx264 --enable-libxvid --enable-opencl --enable-videotoolbox --disable-lzma libavutil 56. 14.100 / 56. 14.100 libavcodec 58. 18.100 / 58. 18.100 libavformat 58. 12.100 / 58. 12.100 libavdevice 58. 3.100 / 58. 3.100 libavfilter 7. 16.100 / 7. 16.100 libavresample 4. 0. 0 / 4. 0. 0 libswscale 5. 1.100 / 5. 1.100 libswresample 3. 1.100 / 3. 1.100 libpostproc 55. 1.100 / 55. 1.100 Hyper fast Audio and Video encoder usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}... Use -h to get full help or, even better, run 'man ffmpeg'
2.pipenv install pydub
でpydubのインストール
普通にこれはインストールできた
$ pipenv install pydub
実行してみる
鳴らす音楽は以下のサイトからダウンロードしておいた
フォルダ構成は以下の通り
. └── sound ├── decision7.mp3 └── sound.py
ソース
import os from pydub import AudioSegment from pydub.playback import play ABS_PATH = os.path.dirname(os.path.abspath(__file__)) def play_sound(): sound = AudioSegment.from_mp3(f'{ABS_PATH}/decision7.mp3') play(sound) if __name__ == '__main__': play_sound()
実行
$ pipenv run python3 sound/sound.py Loading .env environment variables… Input #0, wav, from '/var/folders/93/g9_qrz2519z_p3y0k44pctt00000gn/T/tmpp9zk38i8.wav': Duration: 00:00:00.86, bitrate: 1411 kb/s Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, 2 channels, s16, 1411 kb/s 0.81 M-A: 0.000 fd= 0 aq= 0KB vq= 0KB sq= 0B f=0/0
音楽がなった!!これだけで音楽鳴らせるとかpydubに感謝!!
音楽プレイヤーとか作れるのかな...とか思ったりしてる