如何使用GPIO按钮切换音频播放?

时间:2018-03-12 05:14:49

标签: python audio raspberry-pi raspberry-pi3 raspbian

我想使用相同的按钮播放和暂停音频文件。这个问题的解决方案是什么?请帮我。我正在使用' aplay'哪个玩家具有切换功能? 这是python代码:

import RPi.GPIO as GPIO
import time
import os
import subprocess
GPIO.setmode(GPIO.BCM)

GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) 
while True:
    input_state1=GPIO.input(17)
    if input_state1==False:
        subprocess.call(["aplay", "temp.wav"])

1 个答案:

答案 0 :(得分:0)

看起来您正在配置输入引脚,这就是您目前所做的事情:

  • 按下图钉时,input_state1将为True,您不做任何操作。
  • 当未按下图钉时,input_state1将为False,您正在使用temp.wav播放aplay文件(命令行录音机和ALSA播放器)。

如果我弄错了,请纠正我,但我明白你的意图是使用GPIO引脚作为切换来播放和暂停(即按下时,如果暂停则应播放,如果正在播放则应暂停)。

经过一番搜索,看起来aplay无法像您想要的那样暂停和恢复。如果你仍想使用它,你可以使用这个名为Node-aplay的Node.js的aplay包装器来支持它。更简单的方法是使用mpc,您必须先安装并设置它。之后,您可以尝试使用此代码进行切换:

import RPi.GPIO as GPIO
import time
import os
import subprocess
GPIO.setmode(GPIO.BCM)

GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# this method is invoked when the event occurs
def toggle_state(channel):
    subprocess.call(["mpc", "toggle"]) # toggles between play and pause

# detects GPIO pin press event
GPIO.add_event_detect(17, GPIO.BOTH, toggle_state, 600)

try:
    subprocess.call(["mpc", "add", "temp.wav"]) # adds file to the playlist
    subprocess.call(["mpc", "play"]) # starts playing (may need to mention position)
except KeyboardInterrupt:
    GPIO.cleanup() # clean up GPIO settings before exiting

如您所见,我添加了GPIO.add_event_detect来检测正在按下的GPIO(详细了解此API here)。我已经对代码的作用发表了一些评论。希望这有帮助!

相关问题