本文介绍了Pygame 声音不断重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在比赛结束时播放失败的声音.以前,以下代码适用于 Python 3.5,但在播放声音后会中止.我升级到 python 3.6,现在它只是不断重复.怎样才能把声音播放到最后?

导入pygame定义声音():pygame.mixer.init()sound1 = pygame.mixer.Sound('womp.wav')为真:sound1.play(0)返回
解决方案

while True 是一个无限循环:

while True:sound1.play(0)

声音会连续播放.

使用 get_length() 以秒为单位获取声音的长度.等到声音结束:
(pygame.time.wait() 以毫秒为单位)

导入pygamepygame.mixer.init()my_sound = pygame.mixer.Sound('womp.wav')my_sound.play(0)pygame.time.wait(int(my_sound.get_length() * 1000))

或者,您可以通过 pygame.mixer 测试是否有任何声音被混合.get_busy().只要混合声音就运行循环:

导入pygamepygame.init()pygame.mixer.init()my_sound = pygame.mixer.Sound('womp.wav')my_sound.play(0)时钟 = pygame.time.Clock()而 pygame.mixer.get_busy():时钟滴答(10)pygame.event.poll()

I am trying to play a sound at the end of a game when there is a lose. Previously this code below worked with Python 3.5 but it would abort after it played the sound. I upgraded to python 3.6 and now it just keeps on repeating. How can I play the sound until the end?

import pygame
def sound():
    pygame.mixer.init()
    sound1 = pygame.mixer.Sound('womp.wav')
    while True:
        sound1.play(0)
    return

解决方案

while True is an endless loop:

The sound will be played continuously.

Use get_length() to get the length of the sound in seconds. And wait till the sound has end:
(The argument to pygame.time.wait() is in milliseconds)

import pygame

pygame.mixer.init()
my_sound = pygame.mixer.Sound('womp.wav')
my_sound.play(0)
pygame.time.wait(int(my_sound.get_length() * 1000))

Alternatively you can test if any sound is being mixed by pygame.mixer.get_busy(). Run a loop as long a sound is mixed:

import pygame

pygame.init()
pygame.mixer.init()
my_sound = pygame.mixer.Sound('womp.wav')
my_sound.play(0)

clock = pygame.time.Clock()
while pygame.mixer.get_busy():
    clock.tick(10)
    pygame.event.poll()

这篇关于Pygame 声音不断重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:51