#! /usr/bin/python3
# Script to toggle the sound bar power
from gpiozero import LED
from time import sleep
import subprocess
#from pydub import AudioSegment
#from pydub.playback import play
import glob
import random

pin = 4

def toggleRelay(pin):
    """ Toggles the output pin with a slight delay in-between. """
    print("toggleRelay")
    print(pin)
    snd = LED(pin)
    snd.on()
    sleep(1)
    snd.off()

def getFiles(path):
    """  """
    print("getFiles")
    print(path)
    files = [f for f in glob.glob(path + "**/*.mp3", recursive=True)]
    return files#["/usr/share/alarm-clock-pi/mp3/bensound-tenderness.mp3"]

def getRandomItem(items):
    """  """
    print(items)
    print("getRandomItem")
    return random.choice(items)#items[0]

def playMP3(file):
    """ Plays an mp3-file using bash omx-player. """
    print("playMP3")
    print(file)
    bashCommand = "/usr/bin/omxplayer \"" + file + "\" -o alsa:hw:1,0 --vol -500"# >/dev/null"
    print(subprocess.run(bashCommand, shell=True))
    #song = AudioSegment.from_wav(file)
    #play(song)

def main():
    toggleRelay(pin);
    playMP3(getRandomItem(getFiles("/usr/share/alarm-clock-pi/mp3")))
    toggleRelay(pin)

if __name__ == "__main__":
    main()
    
    
    
    
