LoginSignup
12
14

More than 5 years have passed since last update.

Pythonでフォルダにある音楽をランダムに再生したい

Posted at

初心者なので変なところあるかもしれません。何かあれば指摘してください。

環境 windows10 64bit 1607
   atom 1.12.6
   Python 3.5.2
   pygame 1.9.2b1

mp3を再生する

まずmp3をpythonで再生する方法を探しました。
ディレクトリ構造はこうなっています。

music_play
      |--music.py
      |--test
          |--text1.txt
          |--text2.txt
          |--music1.mp3
          |--music2.mp3
          |--music3.mp3
          |--music4.mp3

音楽を再生するに当たってPygameが便利そうだったのでこれを使うことにしました。

 >pip install pygame
music.py
import pygame

# mixerモジュールの初期化
pygame.mixer.init()
# 音楽ファイルの読み込み
pygame.mixer.music.load("test\music1.mp3")
# 再生回数を指定-1だとループ
pygame.mixer.music.play(1)

print("ctrl+c stop")
while True:
    x = 1

pygame.mixer.music.stop()

pipでpygameをインストールします。
pygameをインポート、初期化、ファイルの読み込み、再生回数の指定といった具合です。
music.playは-1にするとループします。ctrl+Cでストップすることができます。

フォルダの中にあるmp3をリスト化する

今回はフォルダ内のファイルをパス付で取得したかったので「glob」を利用しました。

import glob

x = glob.glob("test\*.mp3")

print(x)
print(x[1])

出力結果
['test\\music1.mp3', 'test\\music2.mp3', 'test\\music3.mp3', 'test\\music4.mp3']
test\music2.mp3

これでxにtestの中の.mp3だけをリスト化できます。
余談で私だけかもしれないですが、atomでプラグインのatom-runerで実行したら違うプロジェクトフォルダの中を表示した?cmdで実行するとうまく表示された。

リスト化したのをシャッフルする

import glob
from random import shuffle

x = glob.glob("test\*.mp3")

shuffle(x)

print(x)
print(x[1])
出力結果例
['test\\music1.mp3', 'test\\music4.mp3', 'test\\music2.mp3', 'test\\music3.mp3']
test\music4.mp3

「glob」でtestの中にあるmp3のファイルをリスト化して「random」でシャッフルします。
さっきはtest\music1.mp3、test\music2.mp3...と続いていたのが1,4,2,3に変化しました。
出力結果は実行するたび毎回変わるので例として挙げておきます。

合わせる

music.py
import pygame
import glob
from random import shuffle

x = glob.glob("test\\*.mp3") #testの中のmp3をリスト化
shuffle(x) #リストをシャッフル

print(x[1])

pygame.mixer.init()
pygame.mixer.music.load(x[1])
pygame.mixer.music.play(2) 

print("ctrl+c stop")
while True:
    x = 1

pygame.mixer.music.stop() # 再生の終了

これで毎回実行するたびに音楽がランダムに再生されるようになりました。

参考

http://nwpct1.hatenablog.com/entry/2013/10/19/161008
http://qiita.com/Nyanpy/items/cb4ea8dc4dc01fe56918
http://qiita.com/da1/items/e1aa136c7ef8fa1c3636

12
14
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
12
14