2013-03-20 69 views
1

目前只是尝试pygame,我创建了一个白色背景,只是一个图像的窗口。我希望能够使用箭头键(正常工作)以及按下箭头键时移动图像,我想要播放引擎声音mp3。这是我目前得到的代码:pygame按键上的声音

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

你的if语句*任何*键(不只是那些4),被释放停止声音。 – ninMonkey 2013-03-20 05:43:32

+0

所以我需要使用4个键的每个子if语句下的pygame.mixer.music.stop()? – 2013-03-20 12:44:26

回答

3

在屏幕上移动,但没有任何声音的那一刻,你的脚本将停止没有按任何键时发出声音。将.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 soundfiles的更多示例如下所示:

http://www.stuartaxon.com/2008/02/24/playing-a-sound-in-pygame/

http://www.pygame.org/docs/ref/mixer.html