按键上的Pygame声音

时间:2013-03-20 04:32:53

标签: python pygame 2d-games

目前只是尝试pygame,我创建了一个白色背景窗口,只是一个图像。我希望能够使用箭头键(工作正常)以及按下箭头键时移动图像,我想要一个引擎声音mp3播放。这是我目前的代码:

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

图像加载正常,我可以在屏幕上移动,但根本没有声音

1 个答案:

答案 0 :(得分:4)

此刻,当没有按任何键时,您的脚本将停止声音。将.stop()命令放在已使用的键的特定键事件中应解决它。

此外,不要将声音播放为:

pygame.mixer.music.play()

正如您所做的那样,将声音播放为您指定的变量:

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



if event.type == KEYDOWN:

            sound.play()

或者,使用以下方式分配声音文件:

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

此处显示了pygame声音文件的更多示例:

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

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