Pygame在按键时播放声音

2 投票
1 回答
6656 浏览
提问于 2025-04-17 19:43

我现在正在尝试使用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 个回答

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

撰写回答