Pygame按键时声音[关闭]

问题描述 投票:2回答:1

[目前仅尝试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()

图像可以很好地加载,我可以在屏幕上移动,但是完全没有声音

python pygame 2d-games
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

© www.soinside.com 2019 - 2024. All rights reserved.