Search code examples
pythonpygame2d-games

Pygame sound on key press


Currently just trying out pygame and I've created a window with a white background and just an image. I want to be able to move the image using the arrow keys (working fine) as well as when an arrow key is being pressed, I want an engine sound mp3 to play. This is the code I've got at the moment:

    image_to_move = "dodge.jpg"

    import pygame
    from pygame.locals import *

    pygame.init()
    pygame.display.set_caption("Drive the car")
    screen = pygame.display.set_mode((800, 800), 0, 32)
    background = pygame.image.load(image_to_move).convert()

    pygame.init()

    sound = pygame.mixer.music.load("dodgeSound.mp3")

    x, y = 0, 0
    move_x, move_y = 0, 0


    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                break

            #Changes the moving variables only when the key is being pressed
            if event.type == KEYDOWN:
                pygame.mixer.music.play()
                if event.key == K_LEFT:
                    move_x = -2
                if event.key == K_RIGHT:
                    move_x = 2
                if event.key == K_DOWN:
                    move_y = 2
                if event.key == K_UP:
                    move_y = -2


            #Stops moving the image once the key isn't being pressed
            elif event.type == KEYUP:
                pygame.mixer.music.stop()
                if event.key == K_LEFT:
                    move_x = 0
                if event.key == K_RIGHT:
                    move_x = 0
                if event.key == K_DOWN:
                    move_y = 0
                if event.key == K_UP:
                    move_y = 0

        x+= move_x
        y+= move_y

        screen.fill((255, 255, 255))
        screen.blit(background, (x, y))

        pygame.display.update()

The image will load fine and I can move around the screen, however no sound at all


Solution

  • At the moment, your script will stop the sound when any key isn't pressed. Putting the .stop() command inside the specific key events for the used keys should solve it.

    Additionally, instead of playing the sound as :

    pygame.mixer.music.play()
    

    as you have done, play the sound as the variable you have assigned:

    sound = pygame.mixer.music.load("dodgeSound.mp3")
    
    if event.type == KEYDOWN:
                sound.play()
    

    Alternatively, assign the sound file using:

    sound = pygame.mixer.Sound("dodgeSound.mp3")
    

    Further examples of pygame soundfiles are shown here:

    http://www.stuartaxon.com/2008/02/24/playing-a-sound-in-pygame/

    http://www.pygame.org/docs/ref/mixer.html