当点击GUI上的某个点时,Pygame会发出声音

时间:2011-11-22 02:18:27

标签: audio button pygame

我是一个业余的,非常缺乏经验的程序员。我一直在研究一个使用Pygame编程的艺术项目。我遇到了障碍,广告无法弄清楚如何做我需要它做的事情。

点击GUI上的特定位置时,我需要它来播放特定的声音。例如,当您单击红色按钮时,它会播放一个显示“红色”的音频文件

我还需要它能够通过在画布部分上单击并拖动来播放声音。

我希望这足够详细。谢谢你的帮助!

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)

1 个答案:

答案 0 :(得分:1)

我认为你应该有一个班级按钮和一组按钮:

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") )
...

然后你可以在主循环中使用它:

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()