Python 按键时播放游戏声音

Python 按键时播放游戏声音,python,pygame,2d-games,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") scree

目前我正在试用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()

图像将加载良好,我可以在屏幕上移动,但是目前根本没有声音,您的脚本将在未按下任何键时停止声音。将.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声音文件的其他示例如下所示:


此时,您的脚本将在未按任何键时停止声音。将.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声音文件的其他示例如下所示:


您的if语句有任何键,而不仅仅是这4个键,正在释放停止声音。因此,我需要在4个键的每个子if语句下使用pygame.mixer.music.stop?您的if语句有任何键,而不仅仅是这4个键,被释放停止声音。所以我需要使用pygame.mixer.music.stop在4个键的每个子if语句下?我知道这是一个旧答案,但链接已断开…我知道这是一个旧答案,但链接已断开。。。