mirror of
https://github.com/apirrone/Open_Duck_Mini_Runtime.git
synced 2025-09-03 03:33:54 +00:00
handling missing sounds better
This commit is contained in:
parent
84dd78a1ec
commit
e556486cd4
1 changed files with 12 additions and 1 deletions
|
@ -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()
|
||||
|
|
Loading…
Reference in a new issue