Pythonで音楽を再生したい(3) pygame編
スドウです。
前回のソースを少し改良してみました。
追加機能は、「一時停止」「再開」ボタンと「音量スライダー」です。
ソースと同じフォルダに sound.wav
を入れておきます。
以下ソースです。
import wave import pygame.mixer as pyx import tkinter as tk def main(): base = tk.Tk() # 再生制御 base2 = tk.Tk() # 音量制御 sound_file = "sound.wav" pyx.init(frequency = 44100, size = -16, channels = 2, buffer = 4096) # 初期設定 sounds = pyx.Sound(sound_file) # 再生ファイルを設定 sd_loop = -1 # 再生階数(-1:無限ループ) channel = sounds.play(loops = sd_loop) # 音楽再生 sound_time = sounds.get_length() # 再生時間取得(曲の長さ, 秒単位) print(sound_time) channel.set_volume(0.5) # 音量初期値 sound_end = channel.get_endevent() # 再生終了時のイベント取得 # 再生/一時停止 def push1(): print('一時停止') channel.pause() # 一時停止 def push2(): print('再開') channel.unpause() # 再開 # 音量調節 def sound_vol(n): channel.set_volume((float)(scale2.get())) button1 = tk.Button(base, text = '一時停止' , command = push1).pack() button2 = tk.Button(base, text = '再開' , command = push2).pack() tk.Label(base2, text = '音量').pack() scale2 = tk.Scale(base2, orient = 'h', from_ = 0.0, to = 1.0, resolution = 0.1 ,command = sound_vol ) scale2.set(0.5) # 音量スライダーの初期値 scale2.pack() base.mainloop() if __name__ == '__main__': main()
IDLEからプログラムを実行すると、sound.wav
が再生されます。
音量注意
一応、音楽の一時停止・再開の機能は実装できました。
(ボタンの数は増えましたが。。。)
また、音楽の再生中に音量の変更ができるようになりました。
ここまでたどり着くのに、かなりの時間を要しましたが、がんばりました(^^;)
ただ実のところ、追加したい機能が他にもいくつかありまして。。。 その内の1つが、現在の再生時間の表示です。
それで、時間表示ができるように変更してるのですが、 以下のソースを実行すると
import wave import pygame.mixer as pyx import time import tkinter as tk def main(): base = tk.Tk() # 再生制御 base2 = tk.Tk() # 音量制御 sound_file = "sound.wav" pyx.init(frequency = 44100, size = -16, channels = 2, buffer = 4096) # 初期設定 sounds = pyx.Sound(sound_file) # 再生ファイルを設定 sd_loop = -1 # 再生階数(-1:無限ループ) channel = sounds.play(loops = sd_loop) # 音楽再生 sound_time = sounds.get_length() # 再生時間取得(曲の長さ, 秒単位) print(sound_time) channel.set_volume(0.5) # 音量初期値 # 再生/一時停止 def push1(): print('一時停止') channel.pause() # 一時停止 def push2(): print('再開') channel.unpause() # 再開 # 音量調節 def sound_vol(n): channel.set_volume((float)(scale2.get())) button1 = tk.Button(base, text = '一時停止' , command = push1).pack() button2 = tk.Button(base, text = '再開' , command = push2).pack() tk.Label(base2, text = '音量').pack() scale2 = tk.Scale(base2, orient = 'h', from_ = 0.0, to = 1.0, resolution = 0.1 ,command = sound_vol ) scale2.set(0.5) # 音量スライダーの初期値 scale2.pack() time_count = 0.0 while pyx.get_busy(): # 音楽再生中のときwhile実行 print(time_count) time.sleep(1) if(time_count < sound_time): time_count += 1 else : time_count = 0.0 base.mainloop() if __name__ == '__main__': main()
whileを使用し再生時間の表示はできました。が、
while以降の処理が実行されずにウィンドウが表示されません。
そのため、一時停止や音量変更の設定が一切できません。
どうしよう。。。
Pythonを学習して日が浅い&オブジェクト指向がほとんどまったくわかっていないので、現状解決策がありません。
これからは、「オブジェクト指向とな何ぞや」という部分も含めてPythonの学習をゆっくり進めていこうかと考えています。
ブログが三日坊主にならなくてよかった
ではでは!
スポンサードリンク