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 に答える