A playerctl module for polybar




playerctl is a simple and lightweight utility that can query and control MPRIS-enabled media players.

Running a simple playerctl pause in the terminal will pause the media player currently playing anything.

As effective as that is, I want something even better: a little button in my polybar that knows when media is playing and when pressed, pauses the player.

So, instead of using an existing functional script, let's write our own.

The polybar module

We need two things: the configuration of the polybar module, and a bash script that the module will call.

Here's the polybar configuration:

type = custom/script
exec = /home/user/.local/bin/polybar_scripts/playerctl.sh
interval = 0.5

This module configuration simply calls the script at the defined path every 0.5 seconds.

Here's the bash script called by the module:

#!/usr/bin/env bash

playerctlstatus=$(playerctl status 2> /dev/null)

if [[ $playerctlstatus ==  "" ]]; then
    echo ""
elif [[ $playerctlstatus =~ "Playing" ]]; then
    echo "%{A1:playerctl pause:}⏸️%{A}"
    echo "%{A1:playerctl play:}▶️%{A}"

Yes, it's not a very nice script, I'm sure it can be improved in many ways but hey, it works.

In short, it first gets the current status of playerctl. If the status is an empty string i.e. there are no media players, return an empty string. This basically "hides" the module.

If the status is the string Playing, return the emoji of a pause button. %{A1:playerctl pause:} will make the button clickable and, when clicked, will run playerctl pause.

Finally, since we know there are media players but none are playing (i.e. the status is Paused), show the play button which does actually what one would expect.

So, is it safe to run this script every 0.5 seconds? Here are some numbers:

$ time /home/user/.local/bin/polybar_scripts/playerctl.sh
# real	0m0,037s
# user	0m0,016s
# sys	0m0,013s

So yes, it's quite fast even on this 2010 ThinkPad x201i, this script can easily run multiple times a second. That's handy because you want the play/pause button to update relative quick after pressing it.

Closing remarks

There you have it, my playerctl module for polybar. Okay, one little detail: I do not actually use the emoji symbols in my script but rather the corresponding glyphs included in the Mononoki nerd font.

You could easily expand the script to show what song is playing using the command explained in my previous blog post. I might do just that soon but for now, a simple button that only appears when music is either playing or paused is exactly what I was looking for.