Ubuntu – How to create a shortcut that executes an xdotool command to simulate a key press

media-buttonsshortcut-keysxdotool

I'm trying to simulate a media key press using a custom shortcut.

So far, I've been able to achieve the simulation I need using the command:

xdotool key XF86AudioPlay

It works perfectly, it pauses or starts the music player every time it is run.

The problem comes when trying to run it as a shortcut.

First I tried to run an alias with a custom shortcut, but it did not work.

As explained on this question:

The commands run by keyboard bindings are not parsed via a shell. Your best bet is to create a directory bin in your homedir.

Next I created the suggested script and named it simplay:

#!/bin/sh
xdotool key XF86AudioPlay

It is located inside a bin folder which is part of the PATH,
this works fine and can be run from any location.

When trying to create the Custom Shortcut, I was unable to get it to execute, the configuration is the following:

Name: test
Command: simplay

Shortcut: Ctrl+Alt+R

After searching a bit more I found another way to execute the shortcut:

gnome-terminal -e simplay

I tried it on a terminal and noticed that when executing it it would rapidly open a new terminal window, execute the child process, pausing the music and immediately close the window.

I changed the command on the shortcut and when hitting it I noticed the same behavior opening a terminal and immediately being closed but this time the child process did not pause the music, which makes me think that the script has been called on all my previous attempts but it is somehow not being able to execute.

How can I solve this problem according to your knowledge?

Best Answer

The issue

Your shortcut is performed at the same time as your simulated key press

If you run a command, simulating a key press, called with ... another key press, you will actually simulate a third key press, which is the combination of both :)

To solve

You need to prevent your shortcut to run at the same time as the simulated key press, in other words, add a delay:

/bin/bash -c "sleep 1 && xdotool key XF86AudioPlay"

Add this command to a shortcut, and it should work.

Note

Of course you can play a bit with the value in sleep 1, to set it to the best value that feels comfortable, depending on how "sticky" the combination is pressed. sleep 0.5 might very well do, and make the shortcut act more promptly.