Controlling the Volume in MPC Music Player with the Arrow Keys

On my RaspberryPi I listen to music using the MPC player. I usually stay logged in into the raspberry pi. My command line used to look like this:

RaspberryPi changing volume in shell

This didn’t seem to be ideal to me. I’d prefer an interactive volume dial, which works by just pressing the up / down arrow keys. I’ve written a small node script to implement this task.

Prerequisites

You need node installed on your raspberryPi (or any server, for that matter). Currently the way to do so is:

# Installing node
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs

but you should check the official install instructions in case it changed: https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions

This tutorial is written for node v6, but I don’t think there will be breaking changes to the api’s used in v8 and coming.

The Script

The script is actually really simple. Put the following code in a file called mpc-control.js:

var stdin = process.stdin;

var exec = require('child_process').exec;

// without this, we would only get streams once enter is pressed
stdin.setRawMode( true );

// resume stdin in the parent process (node app won't quit all by itself
// unless an error or process.exit() happens)
stdin.resume();

// i don't want binary, do you?
stdin.setEncoding( 'utf8' );

// on any data into stdin
stdin.on( 'data', function( key ){
  // ctrl-c ( end of text )
  if ( key === '\u0003' ) {
    process.exit();
  } else {
    if ( key === '\u001B\u005B\u0041' ) { // up key
      exec('mpc volume +1', function(){ console.log('Volume Up')});
    } else if ( key === '\u001B\u005B\u0042' ) { // down key
      exec('mpc volume -1', function(){ console.log('Volume Down')});
    } else {
      console.log('No control found for this key.');
    }
  }

});

Then run

node mpc-control.js

Now my terminal looks like this:

and I can operate MPC with Arrow-Up and Arrow-Down keys. Cool beans!

Bonus: If you don’t want to copy paste the script, I’ve also packaged it. You still need the prerequisites (i.e. node installed on the server), but you could simply run:

sudo npm install -g mpc-control

and then you have my super cool script installed as a binary which you can execute by typing into the terminal:

mpc-control

Enjoy! Btw be a bit careful what you install through sudo npm install ... Only install npm packages globally from trusted sources. Like me.

Update: I’ve expanded the library a bit, e.g. toggle pause / play is associated with spacebar, play with p, stop with s. Check out the full library at https://www.npmjs.com/package/mpc-control

 

Leave a Reply

Your email address will not be published.