# https://pygame.readthedocs.io/en/latest/7_sound/sound.html # https://pygame.org/docs/ref/mixer.html import pygame import pygame.locals import pygame.mixer import random pygame.init() screen=pygame.display.set_mode((240,200)) pygame.display.set_caption('Sound') def makebutton(): global button_rect global beep_rect global beep2_rect # clear screen screen.fill((255,255,255)) # button font2 = pygame.font.Font(None,20) font2.set_underline(True) button_text = font2.render('Play Sound', 1, (10,10,10)) # margin is the distance of the text from the edge of the screen margin = 6 # put the button in the top left hand corner # and keep the return value (a Rect) in a global variable # so that we can detect mouse clicks on it button_rect = screen.blit(button_text, (margin, margin)) # and a second button button_text = font2.render('Beep', 1, (10,10,10)) # put the button in the top middle beep_rect = screen.blit(button_text, (120, margin)) # and a third button button_text = font2.render('Beep2', 1, (10,10,10)) # put the button in the top right hand corner beep2_rect = screen.blit(button_text, (170, margin)) pygame.display.update() def main(): running = True while running: # get one event off the event queue # waiting until there is one event = pygame.event.wait() if event.type == pygame.locals.QUIT: running = False if event.type == pygame.locals.MOUSEBUTTONDOWN: if button_rect.collidepoint(event.pos): # clicking the button plays the sound snd.play() if beep_rect.collidepoint(event.pos): beep.play() if beep2_rect.collidepoint(event.pos): beep2.play() # ignore all other events # start of main program makebutton() # load the sound file just once snd = pygame.mixer.Sound('/usr/share/sounds/alsa/Side_Left.wav') # and another way to make a beep # this only works with Python 3 buff = bytes.fromhex(('10'*60+'F0'*60)*200) beep = pygame.mixer.Sound(buffer=buff) # and a different sound buff = bytes.fromhex(''.join([('10'*(60-i//40)+'F0'*(60-i//40)) for i in range(200)])) beep2 = pygame.mixer.Sound(buffer=buff) # run the main loop in a function main() # if we don't call quit(), the window doesn't close # because another thread is running pygame.quit()