如何使用 GPIO 按钮切换音频播放?
How to toggle audio playback using GPIO push button?
我想使用同一个按钮播放和暂停音频文件。这个问题的解决方案是什么?请帮我。我用的是'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"])
看起来您正在配置一个输入引脚,这就是您目前所做的:
- 当按下 pin 时,
input_state1
将是 True
,您什么都不做。
- 当 pin 未按下时,
input_state1
将是 False
并且您正在使用 aplay
播放 temp.wav
文件(command-line 录音机和播放器对于 ALSA)。
如果我弄错了请纠正我,但我知道你的意图是使用 GPIO 引脚作为切换开关来播放和暂停(即按下时,如果暂停则应该播放,如果正在播放则应该暂停).
稍作搜索后,aplay
似乎无法像您希望的那样暂停和继续。如果您仍然想使用它,您可以使用这个名为 Node-aplay which supports this. Easier way is to use mpc 的 Node.js 的播放包装器,您必须先安装并设置它。之后,您可以尝试使用此代码进行切换:
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)。我也对代码的作用发表了一些评论。希望这对您有所帮助!
我想使用同一个按钮播放和暂停音频文件。这个问题的解决方案是什么?请帮我。我用的是'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"])
看起来您正在配置一个输入引脚,这就是您目前所做的:
- 当按下 pin 时,
input_state1
将是True
,您什么都不做。 - 当 pin 未按下时,
input_state1
将是False
并且您正在使用aplay
播放temp.wav
文件(command-line 录音机和播放器对于 ALSA)。
如果我弄错了请纠正我,但我知道你的意图是使用 GPIO 引脚作为切换开关来播放和暂停(即按下时,如果暂停则应该播放,如果正在播放则应该暂停).
稍作搜索后,aplay
似乎无法像您希望的那样暂停和继续。如果您仍然想使用它,您可以使用这个名为 Node-aplay which supports this. Easier way is to use mpc 的 Node.js 的播放包装器,您必须先安装并设置它。之后,您可以尝试使用此代码进行切换:
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)。我也对代码的作用发表了一些评论。希望这对您有所帮助!