Music Player Daemon (MPD)

Using nc (netcat) to control MPD

A simple way to manage MPD on Linux is via local sockets which can be bound to a name without a socket inode on the filesystem. MPD implements this by prepending @ to the address:

bind_to_address "@MPD"

The setting bind_to_address specifies which addresses MPD listens on for connections from clients. If no port is specified, the default port is 6600.

The command nc calls itself the TCP/IP swiss army knife. nc (netcat) is a simple unix utility which reads and writes data across network connections, using TCP or UDP protocol.

Read more at: https://www.commandlinux.com/man-page/man1/nc.1.html

The following command will return the status of MPD:

echo -e status\\nclose | nc -w 1 localhost 6600

The command will produce an output like the following:

OK MPD 0.20.0
volume: -1
repeat: 1
random: 0
single: 0
consume: 0
playlist: 2
playlistlength: 0
mixraMPDb: 0.000000
state: stop
OK

We can grep parts of the output to read the status of MPD. Here some examples:

Read volume level from MPD

echo -e status\\nclose | nc -w 1 localhost 6600 | grep -o -P '(?<=volume: ).*'

If you want to write the value to a file, you can use the following command. In this example we save the value in the tmp directory in a file called volfile:

echo -e status\\nclose | nc -w 1 localhost 6600 | grep -o -P '(?<=volume: ).*' > /tmp/volfile

Get length of current playlist

PLLENGTH=$(echo -e "status\nclose" | nc -w 1 localhost 6600 | grep -o -P '(?<=playlistlength: ).*')

Get player state

  • play => MPD is playing something
STATE=$(echo -e "status\nclose" | nc -w 1 localhost 6600 | grep -o -P '(?<=state: ).*')

Get current song

currentSong=`mpc current`

At end of playlist, this will be not set!