Взаимодействие Большая кнопка пробела с Raspberry Pi - PullRequest
0 голосов
/ 03 октября 2018

Я работаю над проектом, в котором мне нужно проигрывать 5 mp3 песен в последовательности один за другим.Каждая песня имеет продолжительность 10 с.Для этой цели я использую библиотеку pygame.

Все работает нормально, но я должен добавить одну на будущее в этом приложении, то есть я хочу запустить и приостановить эти mp3-песни при нажатии кнопки BIG, подключенной черезодин из последовательных портов Raspberry Pi (это в основном кнопка пробела).Я хочу, чтобы программа продолжала работать при нажатии кнопки пробела (чтобы не останавливаться, принимая пробел в качестве прерывания)

Я начинающий и не знаю, как это сделать.enter image description here

import time
import random
import RPi.GPIO as GPIO
import pygame
pygame.mixer.init()

# setting a current mode
GPIO.setmode(GPIO.BCM)
#removing the warings 
GPIO.setwarnings(False)
#creating a list (array) with the number of GPIO's that we use 
pins = [16,20,21] 

#setting the mode for all pins so all will be switched on 
GPIO.setup(pins, GPIO.OUT)
GPIO.output(16,  GPIO.HIGH)
GPIO.output(20,  GPIO.HIGH)
GPIO.output(21,  GPIO.HIGH)
temp = ''
new = ''
def call_x():
    GPIO.output(16,  GPIO.LOW)
    time.sleep(10)
    GPIO.output(16,  GPIO.HIGH)

def call_y():
    GPIO.output(20,  GPIO.LOW)
    time.sleep(10)
    GPIO.output(20,  GPIO.HIGH)

def call_z():
    GPIO.output(21,  GPIO.LOW)
    time.sleep(10)
    GPIO.output(21,  GPIO.HIGH)

def song(val):
    if (select == 'a'):
            #1............................................................
            pygame.mixer.music.load("Shinsuke-Nakamura.mp3")
            pygame.mixer.music.play()
            time.sleep(0.2)

            if(val == 'x'):
              call_x()
            if(val == 'y'):
              call_y()
            if(val == 'z'):
              call_z()

            temp = 'a'
            return temp
    if (select == 'b'):
            #2............................................................
            pygame.mixer.music.load("John-Cena.mp3")
            pygame.mixer.music.play() 
            time.sleep(0.2)

            if(val == 'x'):
              call_x()
            if(val == 'y'):
              call_y()
            if(val == 'z'):
              call_z()

            temp = 'b'
            return temp
    if (select == 'c'):
            #3............................................................
            pygame.mixer.music.load("Brock-Lesnar.mp3")
            pygame.mixer.music.play()
            time.sleep(0.2)

            if(val == 'x'):
              call_x()
            if(val == 'y'):
              call_y()
            if(val == 'z'):
              call_z()

            temp = 'c'
            return temp

try:
    while 1:
        select = random.choice('abcdefghij')
        select1 = random.choice('xyz')


        if (temp != select and select1 != new):
            temp = song(select1)
            new = select1
        else:
            print('repeat')

except KeyboardInterrupt:
 GPIO.cleanup()       # clean up GPIO on CTRL+C exit
 pygame.mixer.music.stop()
pygame.mixer.music.stop() 
GPIO.cleanup()           # clean up GPIO on normal exit

1 Ответ

0 голосов
/ 03 октября 2018

Я не знаком с Raspberry Pi, но я могу показать вам, как бы я делал это в "обычной" программе для пигмеев.

Поместите имена ваших музыкальных файлов в список и переключайте песни с помощью функции set_endevent, а также пользовательского типа события и индексной переменной.

Чтобы приостановить воспроизведение, я бы определил логическую переменную paused и переключал бы ее, когда пользователь нажимает Пробел paused = not paused.Затем просто приостановите и отмените воспроизведение музыки следующим образом:

if paused:
    pg.mixer.music.pause()
else:
    pg.mixer.music.unpause()

Вот полный пример:

import random
import pygame as pg


pg.mixer.pre_init(44100, -16, 2, 2048)
pg.init()
screen = pg.display.set_mode((640, 480))

SONGS = ['song1.wav', 'song2.wav', 'song3.wav']
# Here we create a custom event type (it's just an int).
SONG_END = pg.USEREVENT
# When a song is finished, pygame will add the
# SONG_END event to the event queue.
pg.mixer.music.set_endevent(SONG_END)
# Load and play the first song.
pg.mixer.music.load(SONGS[0])
pg.mixer.music.play(0)


def main():
    clock = pg.time.Clock()
    song_idx = 0
    paused = False
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.KEYDOWN:
                # Press right arrow key to increment the
                # song index. Modulo is needed to keep
                # the index in the correct range.
                if event.key == pg.K_RIGHT:
                    print('Next song.')
                    song_idx += 1
                    song_idx %= len(SONGS)
                    pg.mixer.music.load(SONGS[song_idx])
                    pg.mixer.music.play(0)
                elif event.key == pg.K_SPACE:
                    # Toggle the paused variable.
                    paused = not paused
                    if paused:  # Pause the music.
                        pg.mixer.music.pause()
                    else:  # Unpause the music.
                        pg.mixer.music.unpause()
            # When a song ends the SONG_END event is emitted.
            # I just pick a random song and play it here.
            if event.type == SONG_END:
                print('The song has ended. Playing random song.')
                pg.mixer.music.load(random.choice(SONGS))
                pg.mixer.music.play(0)

        screen.fill((30, 60, 80))
        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pg.quit()
...