【问题标题】:Making Pygame Play Sound ONCE让 Pygame 播放声音 ONCE
【发布时间】:2014-04-29 13:26:06
【问题描述】:

我有一小段代码,如果满足 if 语句,就会播放一次声音:

for block in block_list:
    if block.rect.y >= 650 and health >=25 and score < 70:
        player_list.remove(player)
        all_sprites_list.remove(player)
        font = pygame.font.Font("freesansbold.ttf", 30)
        label = font.render("SCORE TARGET NOT MET", 1, YELLOW)
        labelRect = label.get_rect()
        labelRect.center = (400, 250)

        error.play()
        laser.stop()

但是在播放“错误”声音时,它会继续循环,直到 pygame 窗口关闭。有什么办法可以编辑我的代码,让“错误”音效只播放一次?

谢谢。

【问题讨论】:

    标签: python loops audio pygame


    【解决方案1】:

    我猜它会一遍又一遍地播放,因为if 子句的条件仍然是True;对于block_list 中的多个block 对象,可能是True

    您应该以对您的应用程序有意义的方式解决此问题。

    当您不了解大局时,很难给出好的建议,但也许一个简单的标志会帮助您:

    # somewhere
    play_error_sound = True
    
    ...
    
    for block in block_list:
        if block.rect.y >= 650 and health >=25 and score < 70:
            ...
            if play_error_sound:
                play_error_sound = False
                error.play()
    
    # set play_error_sound to True once it is allowed to be played again
    

    P.S.:考虑在应用程序开始时只加载一次Font,而不是在循环中一遍又一遍地加载。此外,您应该缓存所有使用 font.render 创建的 Surface,因为字体渲染也是一项非常昂贵的操作,并且可能是主要的性能瓶颈。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多