2

目前只是在尝试 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()

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

4

1 回答 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

于 2013-03-20T17:14:31.873 回答