camp-atmo/campatmo.py

89 lines
2.3 KiB
Python
Raw Normal View History

2019-08-20 12:11:41 +02:00
#!/usr/bin/env python3
import time
import sys
import random
from glob import glob
from pygame import mixer
tracks_per_type = 2
single_track_types = ["lines"]
2019-08-20 12:41:54 +02:00
sound_volume = 0.5
VERBOSITY = 0
2019-08-20 12:11:41 +02:00
2019-08-20 12:41:54 +02:00
def load_sounds(mixer):
2019-08-20 12:11:41 +02:00
type_names = glob("samples/*/")
type_files = {c.split("/")[1]: glob(c + "/*.ogg") for c in type_names}
2019-08-20 12:11:41 +02:00
types = {}
i = 0
mixer.set_num_channels(
sum(
[
1 if name in single_track_types else tracks_per_type
for name in type_files
]
)
)
2019-08-20 12:41:54 +02:00
v(f"{mixer.get_num_channels()} channels set")
2019-08-20 12:11:41 +02:00
for name in type_files:
types[name] = []
for k in range(1 if name in single_track_types else tracks_per_type):
types[name].append(mixer.Channel(i))
i += 1
sounds = {}
for name, files in type_files.items():
sounds[name] = []
for f in files:
2019-08-20 12:41:54 +02:00
sound = mixer.Sound(f)
sound.set_volume(sound_volume)
sounds[name].append(sound)
2019-08-20 12:11:41 +02:00
random.shuffle(sounds[name])
2019-08-20 12:41:54 +02:00
return types, sounds
2019-08-20 13:12:59 +02:00
def manage_type_queue(name, type_channels, sounds):
try:
next_sound_index = max(
[
sounds[name].index(tt.get_queue() or tt.get_sound())
for tt in type_channels
]
)
except ValueError:
next_sound_index = 0
if next_sound_index >= len(sounds[name]):
random.shuffle(sounds[name])
next_sound_index = 0
for c in type_channels:
if c.get_queue() is not None and len(sounds[name]) > 1:
continue
c.queue(sounds[name][next_sound_index])
if c.get_queue() is None and len(sounds[name]) > 1:
c.queue(sounds[name][next_sound_index + 1])
2019-08-20 12:41:54 +02:00
def main():
mixer.init(frequency=22050 * 2)
types, sounds = load_sounds(mixer)
2019-08-20 12:11:41 +02:00
try:
while True:
2019-08-20 13:12:59 +02:00
for name, type_channels in types.items():
2019-08-20 12:11:41 +02:00
if len(sounds[name]) == 0:
continue
2019-08-20 13:12:59 +02:00
manage_type_queue(name, type_channels, sounds)
2019-08-20 12:11:41 +02:00
time.sleep(1)
2019-08-20 12:41:54 +02:00
types, sounds = load_sounds(mixer)
2019-08-20 12:11:41 +02:00
except KeyboardInterrupt:
print("exit")
sys.exit(0)
2019-08-20 12:41:54 +02:00
def v(*msg):
if VERBOSITY >= 1:
print(*msg)
2019-08-20 12:11:41 +02:00
if __name__ == "__main__":
main()