I’m trying to make it so when I play a random sound from a list, the sounds don’t overlap.
We’ve all seen the iconic NPC who’s saying multiple lines at once when you skip through the dialogue. I want to avoid that.
I’m using this system to play sounds from a directory: (The code plays random sounds,but they overlap.)
import bge import aud from random import choice from bge.logic import expandPath, globalDict from pathlib import Path def getSounds(path): """ Returns a list containing all the audio files paths with specific extensions on the given path. """ sounds =  # Path objects make easier to work with paths path = Path(path).resolve() # Iterates over all files in the given path for _file in path.iterdir(): # Add to list only files with the given extensions if _file.suffix in (".mp3", ".wav", ".ogg"): sounds.append(_file.as_posix()) return sounds def playSound(path, obj): """ Play 3D sound from path in the position of given object. Remember that 3D sound only works with mono audio files. """ # Get the audio device and set its properties according to current camera device = aud.device() device.distance_model = aud.AUD_DISTANCE_MODEL_LINEAR device.listener_location = obj.scene.active_camera.worldPosition device.listener_orientation = obj.scene.active_camera.worldOrientation.to_quaternion() # Create an audio factory and play it, with a handle as result factory = aud.Factory(path) handle = device.play(factory) # Makes the handle behave as a 3D sound handle.relative = False handle.location = obj.worldPosition # If sound source is farther from listener than the value below, volume is zero handle.distance_maximum = 10 def main(): cont = bge.logic.getCurrentController() own = cont.owner spacebar = cont.sensors["Spacebar"] # Load path list of sounds into globalDict if not already loaded if not "Sounds" in globalDict.keys(): globalDict["Sounds"] = getSounds(expandPath("//sounds/")) print("Loaded sound paths to globalDict") # Play a sound then spacebar is pressed if spacebar.positive: # Get a random sound path from loaded sound paths soundToPlay = choice(globalDict["Sounds"]) # Play random sound in the position of current object playSound(soundToPlay, own) print("Played random sound:", soundToPlay) main()
So, the documentation seems to suggest I can check the status of a handle and if the status is 0, then the sound would be done playing.
Problem is, I seem to be missing something, because I can’t figure out how to check a handle’s status. is there a
if handle.status == 0: function, or what?
I appreciate your time.