简体   繁体   English

如何播放声音 1 次

[英]How to play a sound 1 time

The conditional operator checks "if answer_code == NumberX" then the code starts the sound, but due to the fact that it's all in the loop, the sound is played every frame.条件运算符检查“if answer_code == NumberX”,然后代码开始播放声音,但由于它都在循环中,因此每帧都会播放声音。 How do I make the sound play 1 time?如何让声音播放 1 次?

while run:
        timer.tick(fps)  # Контроль времени (обновление игры)
        left_click = False
        events = pygame.event.get()
        for event in events:  # Обработка ввода (события)
            if event.type == pygame.QUIT:  # Проверить закрытие окна
                run = False  # Завершаем игровой цикл
            if event.type == pygame.MOUSEBUTTONDOWN:
                left_click = event.button = 1
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_BACKSPACE:
                    answer_code = answer_code[:-1]
                else:
                    answer_code += event.unicode

        # Рендеринг (прорисовка)

        screen.fill(WHITE)  # Заливка заднего фона
        screen.blit(BackGround.image, BackGround.rect)

        if answer_code == NumberX:
            print_text('Правильно', width // 2 - 400, height // 2 -500, font_color=(0, 255, 0), font_size=200)
            print(answer_code)
            print(valueOne, valueTwo, (valueOne * valueTwo))

            pygame.mixer.Sound.play(win_sound)

        pygame.display.update()  # Переворачиваем экран

You don't have to call pygame.mixer.Sound.play frame.您不必调用pygame.mixer.Sound.play框架。 pygame.mixer.Sound.play only plays the sound in the background. pygame.mixer.Sound.play只在后台播放声音。 The sound is played only when the response is received:只有在收到响应时才会播放声音:

while run:
    timer.tick(fps)  # Контроль времени (обновление игры)
    left_click = False
    events = pygame.event.get()
    for event in events:  # Обработка ввода (события)
        # [...]
            
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                answer_code = answer_code[:-1]
            else:
                answer_code += event.unicode

            if answer_code == NumberX:
                pygame.mixer.Sound.play(win_sound)

    # [...]

    if answer_code == NumberX:
        print_text('Правильно', width // 2 - 400, height // 2 -500, font_color=(0, 255, 0), font_size=200)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM