使用触摸传感器在两个音频文件之间切换

2024-09-27 07:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是想做一件非常简单的事情,我想播放两个不同的声音文件取决于触摸传感器。我目前的问题是,虽然传感器工作,程序不会改变音频文件。。。所以,我现在不知所措,有什么帮助吗? 提前谢谢, 萝拉

import pygame

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN)

pygame.mixer.pre_init(44100, -16, 12, 512)
pygame.mixer.init()
pygame.init()


fastbeat = pygame.mixer.Sound('/home/pi/gpio-music-box/samples/fastbeat.ogg')
fastbeat.set_volume(.4);

slowbeat = pygame.mixer.Sound('/home/pi/gpio-music-box/samples/slowbeat.ogg')
slowbeat.set_volume(.4)

while True:

    if(GPIO.input(7)): #interrupt pin is high

        print ('touched')
        fastbeat.play()

    else: # Interupt pin is low
        print ('not touched')
        slowbeat.play()

我现在将代码更改为:

import pygame

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN)

pygame.mixer.pre_init(44100, -16, 12, 512)
pygame.mixer.init()
pygame.init()


fastbeat = pygame.mixer.Sound('/home/pi/gpio-music-box/samples/fastbeat.ogg')
fastbeat.set_volume(.4);

slowbeat = pygame.mixer.Sound('/home/pi/gpio-music-box/samples/slowbeat.ogg')
slowbeat.set_volume(.4)

while True:

    if(GPIO.input(7)): #interrupt pin is high

        print ('touched')
        slowbeat.stop()
        fastbeat.play()

    else: # Interupt pin is low
        print ('not touched')
        fastbeat.stop()
        slowbeat.play()

这对我来说很管用,但另一个问题是,有没有办法我可以改变我的if命令,让它只播放一次快拍,然后切换回慢拍

你好,萝拉


Tags: importboxhomegpioinitmusicpipygame
1条回答
网友
1楼 · 发布于 2024-09-27 07:24:10

似乎你在无限循环播放慢音-所以没有时间让音频开始播放

试试这个

isButtonUp = true  #was the button untouched?
while True:

if(GPIO.input(7)): #interrupt pin is high
    isButtonUp = false   #button is not untouched
    print ('touched')
    fastbeat.play()

else if (!isButtonUp): #has button been untouched before?
    print ('not touched')
    isButtonUp=true #set button as touched
    slowbeat.play()

相关问题 更多 >

    热门问题