How to play sounds (or run anything) on startup and shutdown with Raspbian

How to play sounds (or run anything) on startup and shutdown with Raspbian

The Raspberry Pi is very handy for fun projects, and sometimes these projects require running specific events (like playing a sound) on startup or shutdown, or even in both instances – for an interactive machine that reacts to user input and presence, for example.

Sounds on startup and shutdown can also be used as a means of confirming those specific actions taking place – startup is complete and shutdown is taking place (and will complete in a very short while).

The following instructions apply to the current versions of Raspbian which employ Systemd for services management. Each service uses two files – the service definition and the executed script – so for both startup and shutdown you’d be using 4 separate files (two of each).

Create the file for the shutdown-handler service /etc/systemd/system/shutdownplay.service
starting from the following content:

[Unit]
Description=Shutdown Play

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/etc/shutdownplay.sh

[Install]
WantedBy=multi-user.target

Then create the filer for the startup-handler service /etc/systemd/system/startupplay.service based on the content below:

[Unit]
Description=Startup Play
After=multi-user.target

[Service]
Type=idle
ExecStart=/etc/startupplay.sh

[Install]
WantedBy=multi-user.target

Edit the two target files with the necessary scripts – the files can be named and placed wherever so desired, but remember to edit their names and paths in all the appropriate places.

You can also only create one of the services (either for startup or for shutdown).

The example content for the startup handler script /etc/startupplay.sh:

#!/bin/bash
/usr/bin/mpg123 /etc/sounds/my_startup_sound.mp3

And shutdown handler script /etc/shutdownplay.sh:

#!/bin/bash
/usr/bin/mpg123 /etc/sounds/my_shutdown_sound.mp3

Next give the proper permissions to the service and script files:
chmod 755 /etc/systemd/system/shutdownplay.service
chmod 755 /etc/systemd/system/startupplay.service
chmod 755 /etc/shutdownplay.sh
chmod 755 /etc/startupplay.sh

Also ensure that the sound files have the necessary read permissions.

Finally activate the services:
systemctl daemon-reload
systemctl enable startupplay.service
systemctl enable shutdownplay.service

You can also test the functioning of the services by manually starting them.

Test the startup sound with
service startupplay.service restart
The shutdown sound will require a service restart to test because the sound is played on service shutdown, not start:
service shutdownplay.service start (nothing will happen)
service shutdownplay.service restart (sound will play)

Leave a Reply