[Linux] Play a warning sound when your laptop battery is low

Kasun Siyambalapitiya
2 min readAug 1, 2020

--

Image Source: https://www.flickr.com/photos/weishaupt-cycles/8738377068

When working on a big project or when watching a movie or a TV series in an extended display, all of a sudden you might have ran out of battery and your laptop got shut off or goes to sleep or hibernation. This is very bad for the battery in terms of its lifetime and if your laptop has a mechanical hard drive (not SSD) sudden power off could damage the data in it.

What if your laptop could give you a warning sound when your battery drops a certain value,continuously ( ex: every 5 minutes) so that you can plug in your laptop at your earliest. Well this is very easy and will take about 5min to configure 😍.

  1. Download a short warning sound from anywhere on the Internet. (if you like you can even play a whole song 😀 but remember, that could drain your battery even more if you are not near it to plug it back).
  2. Install the command line music player `mpg123` by running the following commands in your terminal.
sudo apt-get update -y
sudo apt-get install -y mpg123

3. Create a script file to play the downloaded music if your battery percentage is less than 20 (you can customize this value to anything you want 😀 ) and save it in a desired location with executable permission.

#!/bin/bash# You need to export this environment variable in order to play sound from cron
export XDG_RUNTIME_DIR="/run/user/1000"
currentBatteryPercentage=$(upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep "percentage" | awk '{print $2}')currentBatteryPercentage=${currentBatteryPercentage/\%/}if [ $currentBatteryPercentage -lt 22 ]thenmpg123 /home/kasun/Music/apx_battery_low_aler.mp3 -l 2fi

Note:

  • If upower is not installed in your system run the following commands for installing upower .
sudo apt-get update -y
sudo apt-get install -y upower
  • Replace mpg123 ‘s argument with the path to your downloaded music file (mine is located at `/home/kasun/Music/apx_battery_low_aler.mp3`)

4. Open your crontab file for editing by running the following command in terminal.

crontab -e

Fill in the following to execute our script for every 5min.

*/5 * * * * bash /home/kasun/Documents/Scripts/battery-low.sh

Note:

  • Provide the path to your script file after the sh command (mine is located at `/home/kasun/Documents/Scripts/battery-low.sh`)
  • You can change the scheduled time to anything you want.
  • Please refer https://kb.iu.edu/d/afiz for more details on the crontab.

5. Save the crontab file.

It’s done 😊

Cheers !!!

--

--

Kasun Siyambalapitiya
Kasun Siyambalapitiya

No responses yet