Reputation: 165
I want to create a button in my game that can control the background music on and off. The first click will stop the background music, and the second click can bring back the music. Now my button can control the music on and off, but I need to click multiple times to make it work, it seems that the click event is not captured everytime, here is my code:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if 20 + 50 > mouse_position[0] > 20 and 20 + 20 > mouse_position[1] > 20:
play_music = not play_music
if play_music:
pygame.mixer.music.unpause()
else:
pygame.mixer.music.pause()
pygame.display.flip()
clock = pygame.time.Clock()
clock.tick(15)
Upvotes: 3
Views: 2163
Reputation: 3
ya guys don't need a boolean variable only a small function
def toggleMusic():
if pygame.mixer.music.get_busy():
pygame.mixer.music.pause()
else:
pygame.mixer.music.unpause()
pygame.mixer.music.get_busy() is the boolean you need because this checks if music is playing. if music is playing it will return True and vice versa
Upvotes: 0
Reputation: 20438
J0hn's answer is correct. Define a boolean variable (e.g. music_paused = False
), toggle it when the user clicks on the button and call pygame.mixer.music.pause
to stop the music and pygame.mixer.music.unpause
to resume the playback of the music stream.
I also recommend doing the collision check in the event loop (for event in pygame.event.get():
), because the button should be clicked only once per pygame.MOUSEBUTTONDOWN
event. pygame.mouse.get_pressed()
will keep clicking the music button as long as the mouse button is down.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue1')
pg.mixer.music.load('your_music_file.ogg')
pg.mixer.music.play(-1)
button = pg.Rect(100, 150, 90, 30)
music_paused = False
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
if button.collidepoint(event.pos):
# Toggle the boolean variable.
music_paused = not music_paused
if music_paused:
pg.mixer.music.pause()
else:
pg.mixer.music.unpause()
screen.fill(BG_COLOR)
pg.draw.rect(screen, BLUE, button)
pg.display.flip()
clock.tick(60)
pg.quit()
Upvotes: 7
Reputation: 570
It looks like you have a pygame.mixer.music.pause()
but nothing from resume
. I'm not sure how pygame's music mixer works but I'd recommend using a flag that is updated on button click
music = 0
by default, if clicked, set music = 1
then have a check if music == 1: pygame.mixer.music.pause()
and if music == 0: pygame.mixer.music.unpause()
. Make that check and flag change every time the button is clicked.
Upvotes: 6