Play an audio file (or a text-to-speech message) when item state changed

Here’s a simple “Panic Button” script that will play a sound file (or a text-to-speech message) when item ToggleItemName changed state. I created it to be able to help our daughter when she needs assistance in the bathroom…

The ToggleItemName is actually an IKEA Trådfri control outlet. The remote switch is conveniently located in the bathroom. Ideally it should be a pushbutton.

from core.rules import rule
from core.triggers import when

from core.actions import LogAction

from core.actions import Voice
from core.actions import Audio

from org.joda.time import DateTime


rule_init_timestamp = DateTime.now()
logTitle = "voice_notifications.py@{ts}".format(
    ts=rule_init_timestamp.toString("HH:mm:ss")
)


class defaults:
    voice_id = "picotts:enGB"
    notification_volume = 50  # Percentage (integer)
    audio_sink = "sonos:XXX:RINCON_YYY"


@rule("Bathroom assistance requested")
@when("Item ToggleItemName changed")
def Rule_BathroomAssistanceRequested(event):
    global logTitle
    logPrefix = "Rule_BathroomAssistanceRequested(): "

    voiceMsg = "Parental assistance requested in the bathroom."
    file_name =  "doorbell.mp3"

    # Uncomment the following line to issue a voice notification (text-to-speech):
    # Voice.say(voiceMsg, defaults.voice_id, PercentType(defaults.notification_volume))

    # Uncomment the following line to play a sound file
    Audio.playSound(defaults.audio_sink, file_name, PercentType(defaults.notification_volume))

    LogAction.logWarn(logTitle, logPrefix + voiceMsg)

Audio files must be stored in $OPENHAB_CONF/sounds/. The following file formats are supported: WAV, MP3. However it seems that some WAV or MP3 audio files cannot be played, probably due to file-specific encoding differences. Note that the Sonos binding cuts off any notification that exceeds 20 seconds.

I installed picotts as Text-To-Speech synthesizer on a Raspbery Pi 3B+. Here’s how to install it.

Have fun!

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.