Turn The Radio Volume Down For Adverts and DJs talking.

A script for automatically lowering the volume during radio advertisements and DJ announcements and turns the volume back up when songs are playing. It controls a Sonos speaker using the Soco-cli Python library when Tunein is being used.

# Radio control.
# Sets volume low when radio is not playing a song (Talking or Ad Break) on TuneIn.
# Docs https://github.com/avantrec/soco-cli/blob/v0.4.52/README.md
import time
from soco_cli import api

quiet_volume = "15" # Volume for Advertising breaks or Talking.

# Get current volume to set volume to after we have turned it down
exit_code, previous_volume, error = api.run_command("Main Office", "volume")
print("Starting volume is ", previous_volume)

while(True):

    # See if someone has changed the volume and record that
    exit_code, current_volume, error = api.run_command("Main Office", "volume")
    if int(current_volume) > int(quiet_volume):
        previous_volume = current_volume
        print("Volume changed to ", previous_volume)

    # Find what song if any is playing
    exit_code, output, error = api.run_command("Main Office", "track")
    print(output)

    # See if track details have an artist which tells us a song is playing
    if "Artist" in output:
        print ("Playing a song. Set volume to", previous_volume,".")
        exit_code, new_volume, error = api.run_command("Main Office", "volume", previous_volume)
    else:
        print ("Not playing a song. Set volume to", quiet_volume)
        exit_code, text, error = api.run_command("Main Office", "volume", quiet_volume)

    time.sleep(5)