1

I am working on a project in which I have to play 5 mp3 songs in a sequence one after another. Each song has a duration of 10s. For that purpose, I am using pygame library.

All is working fine but I have to add one for future in this application that is I want to start and pause these mp3 songs on pressing BIG Button that is connected through one of the serial port of Raspberry Pi (It's basically a spacebar button). I want program keep on running on pressing spacebar button(not to stop by taking space as an interrupt)

I am a beginner level and don't know how to do this. 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
Ammar Ashraf
  • 61
  • 3
  • 10

1 Answers1

2

I'm not familiar with the Raspberry Pi, but I can show you how I'd do this in a "normal" pygame program.

Put the names of your music files into a list and switch the songs with the help of the set_endevent function and a custom event type and an index variable.

To pause the playback, I'd define a paused boolean variable and toggle it when the user presses Space paused = not paused. Then just pause and unpause the music in this way:

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

Here's a complete example:

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()
skrx
  • 19,980
  • 5
  • 34
  • 48
  • I don't want to play the full song, I want play a song for just 10 seconds. How should I do that? – Ammar Ashraf Oct 03 '18 at 12:23
  • Furthur more music speed is too fast (not playing with normal speed!) – Ammar Ashraf Oct 03 '18 at 12:29
  • I am done with chosing random song for 10 sec, my modified code is provided below, now I just need to integrate a space bar button,on first press mustic starts & on second press music stops and keep on... – Ammar Ashraf Oct 03 '18 at 12:45
  • 1
    Here are several ways to implement a timer in pygame: https://stackoverflow.com/questions/30720665/countdown-timer-in-pygame. After 10s have elapsed, you could just increment the index and play the next song. --- *"Furthur more music speed is too fast (not playing with normal speed!)"* Maybe that has to do with the Raspberry Pi or the files (take a look at [this question](https://stackoverflow.com/questions/2159365/pygame-audio-playback-speed)). I also can't help with the input handling. – skrx Oct 03 '18 at 14:03