in this app i use mpg321 as player for tts,
i have no player in hass.
but i use vlc (through appdaemon) to play radio.
in my app i check if radio is playing, and set it out during speach.
my latest complete (and working correct) version is:
###########################################################################################
#
# Rene Tode ( [email protected] )
#
# 2016/12/21 Germany
#
###########################################################################################
# you need to install gtts and mpg321
# that can be done by:
#
# pip3 install gtts
# sudo apt-get install mpg321
#
# save this app in your app dir with name: sound.py
#
###########################################################################################
# in the appdaemon configfile you need to set:
#
# [soundfunctions]
# module = sound
# class = sound
# soundfilesdir = /an/empty!!/temp/file/dir/
#
###########################################################################################
# then you can use it like this in any app
#
# sound = self.get_app("soundfunctions")
# sound.say("Any text you like","your_language","your_priority")
#
# supported languages: * 'af' : 'Afrikaans'
# * 'sq' : 'Albanian'
# * 'ar' : 'Arabic'
# * 'hy' : 'Armenian'
# * 'bn' : 'Bengali'
# * 'ca' : 'Catalan'
# * 'zh' : 'Chinese'
# * 'zh-cn' : 'Chinese (Mandarin/China)'
# * 'zh-tw' : 'Chinese (Mandarin/Taiwan)'
# * 'zh-yue' : 'Chinese (Cantonese)'
# * 'hr' : 'Croatian'
# * 'cs' : 'Czech'
# * 'da' : 'Danish'
# * 'nl' : 'Dutch'
# * 'en' : 'English'
# * 'en-au' : 'English (Australia)'
# * 'en-uk' : 'English (United Kingdom)'
# * 'en-us' : 'English (United States)'
# * 'eo' : 'Esperanto'
# * 'fi' : 'Finnish'
# * 'fr' : 'French'
# * 'de' : 'German'
# * 'el' : 'Greek'
# * 'hi' : 'Hindi'
# * 'hu' : 'Hungarian'
# * 'is' : 'Icelandic'
# * 'id' : 'Indonesian'
# * 'it' : 'Italian'
# * 'ja' : 'Japanese'
# * 'ko' : 'Korean'
# * 'la' : 'Latin'
# * 'lv' : 'Latvian'
# * 'mk' : 'Macedonian'
# * 'no' : 'Norwegian'
# * 'pl' : 'Polish'
# * 'pt' : 'Portuguese'
# * 'pt-br' : 'Portuguese (Brazil)'
# * 'ro' : 'Romanian'
# * 'ru' : 'Russian'
# * 'sr' : 'Serbian'
# * 'sk' : 'Slovak'
# * 'es' : 'Spanish'
# * 'es-es' : 'Spanish (Spain)'
# * 'es-us' : 'Spanish (United States)'
# * 'sw' : 'Swahili'
# * 'sv' : 'Swedish'
# * 'ta' : 'Tamil'
# * 'th' : 'Thai'
# * 'tr' : 'Turkish'
# * 'vi' : 'Vietnamese'
# * 'cy' : 'Welsh'
#
# for priority give "1","2","3","4" or "5"
#
###########################################################################################
# you can also use:
#
# sound = self.get_app("soundfunctions")
# sound.playsound("any valid mp3 file","your_priority")
#
# to put music in your soundlist (or sounds)
#
###########################################################################################
import appdaemon.appapi as appapi
import datetime
import tempfile
import subprocess
import os
import time as timelib
from gtts import gTTS
class sound(appapi.AppDaemon):
def initialize(self):
self.lasttime = datetime.datetime.now()
self.totaltime = datetime.timedelta(seconds=1)
self.aantalloops = 1
self.minutesrunning = 0
self.herstarts = 0
self.sound_handle = self.run_in(self.check_soundlist,30,normal_loop="running")
self.listen_state(self.extrastart,"input_boolean.geluidforceren")
runtime = datetime.datetime.now() + datetime.timedelta(minutes=15)
self.run_every(self.autoherstart,runtime,15*60)
def autoherstart(self, kwargs):
#self.log("start autoherstart")
counter = 0
counter2 = 1
handletest = "leeg"
while handletest == "leeg" and counter < 30:
try:
time, interval, kwargs = self.info_timer(self.sound_handle)
handletest = kwargs["normal_loop"]
counter = 60
except:
handletest="leeg"
counter = counter + 1
counter2 = counter
timelib.sleep(1)
#self.log("handle kwarg: " + handletest + " aantal keer getest: " + str(counter2))
if handletest != "running":
self.cancel_timer(self.sound_handle)
self.lasttime = datetime.datetime.now()
self.totaltime = datetime.timedelta(seconds=1)
self.minutesrunning = 0
self.herstarts = self.herstarts + 1
self.sound_handle2 = self.run_in(self.check_soundlist,2,normal_loop="restarted")
#self.log("geluidsmodule herstart automatisch geforceerd")
#else:
#self.log("geluidsmodule loopt nog correct")
def extrastart(self, entity, attribute, old, new, kwargs):
self.cancel_timer(self.sound_handle)
self.sound_handle2 = self.run_in(self.check_soundlist,2,normal_loop="restarted")
self.turn_off("input_boolean.geluidforceren")
self.log("geluidsmodule herstart geforceerd")
def check_soundlist(self, kwargs):
try:
priority = self.read_prioritylist()
fname = priority["fname"]
tempfile = priority["tempfile"]
tempfname = priority["tempfilename"]
if fname != "":
self.play(fname)
if tempfile == "1":
os.remove(fname)
os.remove(tempfname)
except:
self.log("PROBLEM IN CHECK_SOUNDLIST")
self.sound_handle = self.run_in(self.check_soundlist,2,normal_loop="running")
actualtime = datetime.datetime.now()
timedifference = actualtime - self.lasttime
self.lasttime = actualtime
if timedifference < datetime.timedelta(seconds=1):
self.log("LOOP RUNNING MORE THEN ONCE")
self.aantalloops = 2
else:
self.totaltime = self.totaltime + timedifference
minutesrunning = self.totaltime.seconds
minutesrunning = minutesrunning//60
if minutesrunning > (self.minutesrunning + 15):
self.minutesrunning = minutesrunning
self.log("SOUNDFILE RUNS CORRECTLY SINCE: " + str(self.totaltime) + " RESTARTED: " + str(self.herstarts) + " TIMES. LOOPAMOUNT: " + str(self.aantalloops))
def say(self,text,lang,priority):
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
fname = f.name
tts = gTTS(text=text, lang=lang)
tts.save(fname)
self. write_in_prioritylist(priority,fname,"1")
def playsound(self,file,priority):
self. write_in_prioritylist(priority,file,"2")
def play(self,filename):
opnieuwaan = False
if self.get_state("input_boolean.swr3")=="on":
self.turn_off("input_boolean.swr3")
opnieuwaan = True
cmd = ['mpg321',filename]
with tempfile.TemporaryFile() as f:
subprocess.call(cmd, stdout=f, stderr=f)
f.seek(0)
output = f.read()
if opnieuwaan:
self.turn_on("input_boolean.swr3")
def write_in_prioritylist(self,priority,file,tempfile):
try:
runtime = datetime.datetime.now().strftime("%d-%m-%y %H:%M:%S.%f")
log = open(self.args["soundfilesdir"] + priority + "_" + tempfile + "_" + file[-10:], 'w')
log.write(runtime + ";" + file)
log.close()
except:
self.log("SOUNDFILEDIR PROBLEM!!")
def read_prioritylist(self):
toppriority = 0
activefile = ""
firsttime = datetime.datetime.strptime("31-12-2050","%d-%m-%Y")
activetemp = ""
activefnamefile = ""
filelist = os.listdir(self.args["soundfilesdir"])
if filelist:
for file in filelist:
priority = int(file[0])
tempfile = file[2]
tempfilename = self.args["soundfilesdir"] + file
fnamefile = open(tempfilename, 'r')
for line in fnamefile:
splitline = line.split(";")
fname = splitline[1]
#self.log(splitline[0])
fdate = datetime.datetime.strptime(splitline[0],"%d-%m-%y %H:%M:%S.%f")
fnamefile.close()
if priority >= toppriority:
if firsttime > fdate:
#self.log(firsttime.strftime("%d-%m-%y %H:%M:%S.%f") + " > " + fdate.strftime("%d-%m-%y %H:%M:%S.%f"))
firsttime = fdate
toppriority = priority
activefile = fname
activetemp = tempfile
activefnamefile = tempfilename
return {"fname":activefile,"tempfilename":activefnamefile,"tempfile":activetemp}