iot-platform-raspberry/birbnetes_iot_platform_raspberry/playback_stuff.py

39 lines
1.1 KiB
Python

import simpleaudio
import random
import os
import os.path
import logging
class ShuffledFolderPlayer:
def __init__(self, folder: str):
self._sounds = []
for folder_element in os.listdir(folder):
self._sounds.append(
simpleaudio.WaveObject.from_wave_file(os.path.join(folder, folder_element))
)
def play_one_random(self):
# noinspection PyBroadException
try:
random.choice(self._sounds).play()
except Exception as e: # simpleaudio seems like it does not expose the exceptions it may raise. So we just log it and call it a day
logging.warning(f"Could not play sound file! {e}")
pass
class BirbnetesIoTPlatformPlaybackDriver:
shuffled_folder_player = None
@classmethod
def init(cls, folder: str = '/var/lib/birbnetes/enemy_soudns'):
cls.shuffled_folder_player = ShuffledFolderPlayer(folder)
@classmethod
def play_one_random(cls):
cls.shuffled_folder_player.play_one_random()
@classmethod
def cleanup(cls):
simpleaudio.stop_all()