handling missing sounds better

This commit is contained in:
apirrone 2025-04-06 12:20:34 +02:00
parent 84dd78a1ec
commit e556486cd4

View file

@ -3,11 +3,13 @@ import time
import os
import random
class Sounds:
def __init__(self, volume=1.0, sound_directory="./"):
pygame.mixer.init()
pygame.mixer.music.set_volume(volume)
self.sounds = {}
self.ok = True
for file in os.listdir(sound_directory):
if file.endswith(".wav"):
@ -17,8 +19,14 @@ class Sounds:
print(f"Loaded: {file}")
except pygame.error as e:
print(f"Failed to load {file}: {e}")
if len(self.sounds) == 0:
print("No sound files found in the directory.")
self.ok = False
def play(self, sound_name):
if not self.ok:
print("Sounds not initialized properly.")
return
if sound_name in self.sounds:
self.sounds[sound_name].play()
print(f"Playing: {sound_name}")
@ -26,13 +34,16 @@ class Sounds:
print(f"Sound '{sound_name}' not found!")
def play_random_sound(self):
if not self.ok:
print("Sounds not initialized properly.")
return
sound_name = random.choice(list(self.sounds.keys()))
self.sounds[sound_name].play()
# Example usage
if __name__ == "__main__":
sound_player = Sounds(1.0, "../../scripts")
sound_player = Sounds(1.0, "../assets/")
time.sleep(1)
while True:
sound_player.play_random_sound()