user1058933
user1058933

Reputation: 1

Pygame play a sound when click on certain spot on GUI

I'm an amateur, very inexperience programmer. I've been working on an art project that I am programming using Pygame. I've hit a road block, ad can't figure out how to do what I need it to do.

I need it to play a specific sound when clicking on a specific place on the GUI. For example, when you click on the red button, it plays an audio file that says "red"

I also need it to be able to play sounds with clicking and dragging on the canvas part.

I hope this is enough detail. Thanks for the help!

the GUI is the gif image

import pygame, sys, time, random
from pygame.locals import *

# set up pygame
pygame.init()
pygame.mixer.init

pygame.mixer.get_init
bgimg="GUIsmall.gif"
inst="instructionssm.gif"
white=(255,255,255)

screen=pygame.display.set_mode((800,600), pygame.RESIZABLE)
screen.fill(white)

bg=pygame.image.load(bgimg)
instrimg=pygame.image.load(inst)

screen.blit(bg, (0,0))

pygame.display.flip()

red=pygame.mixer.Sound("red.mp3")

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            raise SystemExit
        elif event.type==pygame.MOUSEBUTTONDOWN:
            red.play(0,0,0)

Upvotes: 0

Views: 1903

Answers (1)

pmoleri
pmoleri

Reputation: 4449

I think you should have a class button and a collection of buttons:

class Button:

    __init__(self, name, position, image_file, sound_file):
         self.name = name
         self.image = pygame.image.load(image_file)
         self.sound = pygame.mixer.Sound(sound_file)
         self.position = position

         self.rect = pygame.Rect(position, self.image.get_size())

buttons = []
buttons.add( Button("red", (0,0), "red.png", "red.mp3") )
...

Then you can use it in the main loop:

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            raise SystemExit
        elif event.type==pygame.MOUSEBUTTONDOWN:
            for b in buttons:
                 if b.rect.collidepoint(event.pos):
                      b.sound.play()

Upvotes: 1

Related Questions