简体   繁体   English

Python Kivy:一次播放多次声音

[英]Python Kivy: Play sound multiple times at once

I am using Python Kivy for an Android Game. 我正在将Python Kivy用于Android游戏。 I want to play a sound on an event 我想在事件上播放声音

sound = SoundLoader.load("sound.wav")
def onEvent():
    sound.play()

, and It works. ,并且有效。 But now the problem: Of course an event can, and in my case will happen again before the sound is done playing from the last event. 但是现在的问题是:当然可以发生一个事件,在我看来,从最后一个事件开始播放声音之前,事件将再次发生。 And as the sounds are based on a play/pause idea I am getting a problem playing multiple sounds of the same object at once. 由于声音是基于播放/暂停的想法,因此在一次播放同一对象的多个声音时遇到了问题。 That can be solved like this for first: 首先可以这样解决:

onEvent():
    SoundLoader.load("sound.wav").play()

As this creates a new object all the time, and so is able to play it the same time another event plays the sound. 由于这将始终创建一个新对象,因此能够在另一个事件播放声音的同时播放它。 But the problem using this method is quite obvious, because the sound must be loaded everytime the event occurs, and so causes a delay until it's played. 但是使用此方法的问题非常明显,因为每次事件发生时都必须加载声音,因此会导致播放之前的延迟。

Is there a more useful way to do this? 有没有更有用的方法来做到这一点?

{ if you don't understand what I am talking about, or just don't see the problem, feel free to ask } {如果您不明白我在说什么,或者只是看不到问题,请随时提问}

You can workaround this by loading multiple instances of the sound. 您可以通过加载声音的多个实例来解决此问题。 For instance 例如

sounds = [SoundLoader.load("sound.wav") for _ in range(10)]
index = 0

and then 接着

def play():
    sounds[index].play()
    index = (index + 1) % len(sounds)

The more sounds you load, the more instances you can have playing at the same time (in this example 10). 您加载的声音越多,您可以同时播放更多实例(在此示例中为10)。

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

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