Pythonで非同期処理でwav(mp3)を鳴らす
スポンサーリンク
キー(0)を押すと、非同期でマルチプロセスでwav(やmp3)を鳴らすプログラム。subprocessモジュールとpygameでできました。
ファイル構成
parent.py ・・・ 呼び出し元プログラム
child.py ・・・ 呼び出されるプログラム
music.mp3 ・・・再生対象のmp3
parent.py
import subprocess
import time
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
f = open('text.txt', 'w')
while True:
getch = _Getch()
x = getch()
if (int(x) == 0):
f.write(x + "exit \n")
print "\n"
print "boooom!!!!"
p = subprocess.Popen(['python','music.py'])
f.close()
child.py の中身
import pygame.mixer
import time
pygame.mixer.init()
pygame.mixer.music.load('music.mp3')
pygame.mixer.music.play(1) # loop count
time.sleep(200)
pygame.mixer.music.stop()
その他(アナログセンサーから値を読み込んで、、、とかのイメージ)
上の仕組みをRaspberry pi上でPythonでGPIOからの入力に応じて、マルチプロセスで操作を行うこともできますね。例えば、ボタンを押したら、単音(3秒)流れる仕組みとする。その際、ボタンを連打した場合、1回めの再生音の終了を待たずに次の音を再生すると言った様に複数プロセスで出力をさせるなど。(以下ではGPIOからの入力を取得する方法そのものは省いています)GPIOからのアナログセンサー値の取得方法はこちら。
import subprocess //マルチプロセッシングをするためのモジュール
while True:
//readadc関数(GPIOのアナログ入力を取得するオリジナル関数。自分で作る)
trim_pot = readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
// もしtrim_pot(GPIOの入力値)が 200を超えたら
if trim_pot > 200:
p = subprocess.Popen(['python','child.py'])
time.sleep(0.5)
[参考]
- subprocessについて