raspberry piを使ってボタンが押されたらリストの中の音楽がランダムで再生される物を作っています。
現在下記のコードでボタンが押されたらリストの中の音楽がランダムで再生されるところまでは行ったのですが、続けてボタンを押してしまうと重ねて音楽が再生されてしまいます。
プログラミングを習いたてでまだ応用が効かずこちらに質問させていただきました。
python
1#!/usr/local/bin/python 2# -*- coding: utf-8 -*- 3 4from __future__ import print_function 5 6import RPi.GPIO as GPIO 7import os 8import time 9import random 10import shlex 11import subprocess 12 13# Pin Number 14PIN = 19 15 16GPIO.setmode(GPIO.BCM) 17GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) 18last_pin_status = 0 19 20SONG_DIR = '/home/pi/Music/' 21SONG_LIST = ['song1.wav', 'song2.wav'] 22 23 24def play_song(): 25 song = random.choice(SONG_LIST) 26 song_path = os.path.join(SONG_DIR, song) 27 command = 'aplay %s' % (song_path) 28 print(command) 29 subprocess.Popen(shlex.split(command)) 30 31 32while True: 33 pin_status = GPIO.input(PIN) 34 if last_pin_status == 1 and pin_status == 0: 35 play_song() 36 37 last_pin_status = pin_status 38 time.sleep(0.1) 39 40GPIO.cleanup() 41 42
再度ボタンが押されたら
1 再生している音楽を停止する
2 リストの中からランダムで再生する
という2つの条件を入れれば良いと考えて、まずボタンが押されたら音楽を停止するために
if last_pin_status == 1 and pin_status == 0:
play_song()
の後に
if last_pin_status == 1 and pin_status == 0:
stop_song()
を入れました。
python
1 if last_pin_status == 1 and pin_status == 0: 2 play_song() 3 if last_pin_status == 1 and pin_status == 0: 4 stop_song()
こちらで試したところ、停止するどころか、重ねて音楽も再生されませんでした。
どこが問題なのでしょうか?
def stop_songを定義していませんでした。
回答1件
あなたの回答
tips
プレビュー