Best of MPD/MPC Scripts

I've given up on the flashy (GUI) music players. XMMS, Beep-Media-Player, Rhythmbox, Munie... Frikk em! It's time to go terminal (CLI) with the MusicPlayerDaemon and MusicPlayerClient/NCurseMCP. MPD and MPC/NCMPC is simple enough to install and use to play music (with a _cool_ 22MHz of CPU and 6MB of RAM usage) on one local machine, yet the usage still feels a bit clumsy. In comes a few scripts and hacks snipped from musicpd.org/forum. First off, I didn't write any of these scripts. Most are licenced GNU GPL, and the other are simple here for archive. See appended URL for credits and sources. Make sure you have MPC installed (aptitude -P install mpc)

mg (mpc grep)

From: http://www.musicpd.org/forum/index.php?topic=773.0 What it does is search through mpd's database, by filename, for whatever you give it. You don't have to quote anything either. mg also takes what you searched for and puts it into ~/.mg-lookup, which is used later to good effect. Example: mg Behind Blue Eyes
#!/bin/bash
mpc search filename "$*" | tee ~/.mg-lookup

ma (mpc add)

From: http://www.musicpd.org/forum/index.php?topic=773.0 This one has two modes of operation. If you just run it on command line without any arguments it will take all of the files found by the last 'mg' call (this is where ~/.mg-lookup comes in handy) and adds to the playlist. You can also use 'ma' with arguments. In that case, it will search through mpc's database just like mg would, except it will immediately add anything it finds to the playlist. This is useful if you're sure of what the search will return and want to cut out the middleman.
#!/bin/bash
if [ "$1" = "" ]; then
cat ~/.mg-lookup | mpc add
else
mpc search filename "$*" | mpc add
fi

mpg (mpc playlist grep)

From: http://www.musicpd.org/forum/index.php?topic=773.0 This will simply grep the current playlist for all arguments given to it. [coolcode lang="bash" download="mpg"]#!/bin/bash mpc playlist | grep -i "$*"[/coolcode]

mga (mpc grep albums)

From: http://www.musicpd.org/forum/index.php?topic=773.msg3553#msg3553 What it does is search through mpd's database, by album, for whatever you give it.
#!/bin/bash
mpc search filename "$*" | tee ~/.mg-lookup | awk -F/ '{print $2 " - "$3}' | uniq | sort

mhtml (mpc playlist 2 html)

Goto: http://www.musicpd.org/forum/index.php?topic=440.0

m3u 2 mpc

From: http://www.musicpd.org/forum/index.php?topic=287.msg1391#msg1391
#!/bin/sh
mpc clear
cat $1 | mpc add
mpc play

pls 2 mpc

From: http://www.musicpd.org/forum/index.php?topic=287.msg1391#msg1391
#!/bin/sh
mpc clear
grep '^File[0-9]*' $1 | sed -e 's/^File[0-9]*=//' | mpc add
mpc play

Tiny cached PHP "now playing" script

Goto: http://www.musicpd.org/forum/index.php?topic=939.msg4082#msg4082

Irssi MPD client

Goto: https://svn.musicpd.org/iMPD/trunk/iMPD.pl

Playlistbuilder

This is the BEST hack on this page... the mpc playlist is dull, no more! Simply get this script and run playlistbuilder and have your playlist filled with _simular_ songs. Oh, I've slightly modified this, added some instructions and changed up the playlist build. Still... The guy/gal who made this is WONDERFUL! Thanks. :-)
#! /usr/bin/env ruby

# required gems: scrobbler, librmpd

# Licence: GNU GPLv2
# Author: jonas@fs.ei.tum.de

## ABOUT PLAYLISTBUILDER
# http://mpd.wikia.com/wiki/Client:Playlistbuilder
#
# Get the artist of the current song, look up some similar artists,
# search your mpd-music for these artists and add 10 random songs of them to the playlist

#  playlistbuilder
#
# Look up your music for artists similar to the Arctic Monkeys and the Kaiser Chiefs
# and add 5 similar songs each

#  playlistbuilder -i 5 "arctic monkeys" "kaiser chiefs"
#
# Use the -p (--pretend) switch to do all but the actual appending.
# Use the -m (--match) to give an other match-level
#  (default 90, lower means the artist is less similar but you may got more matches within your music).
# Use -s (--silent) to supress non-error output.
# With -n (--no-mpd) you can disable the MPD-interaction and only see the list of similar artists.

## INSTALLATION
# wget https://trac.fs.ei.tum.de/musik/browser/mpd/playlistbuilder/playlistbuil...
#
# wget http://rubyforge.org/frs/download.php/15722/librmpd-0.1.1.gem
# sudo gem install librmpd-0.1.1.gm
#
# sudo gem install scrobbler
#

require "rubygems"
require "scrobbler"
require "librmpd"

class Array
  def random
    # implement a sort of random-choice
    self[rand(self.length)]
  end
end

class MPD
  def self.new_connection
    host = ( ENV['MPD_HOST'] or 'localhost' )
    port = ( ENV['MPD_PORT'] or 6600 )
    mpd = self.new host, port
    try = 0
    begin
      puts "connecting to #{host}:#{port}..." if $options.verbose
      mpd.connect
    rescue RuntimeError
      try += 1
      unless try > 3
         $stderr.puts "connection failed on #{try}. attempt, retrying..."
         retry
      else
         $stderr.puts "unable to connect"
         exit 1
      end
    end
    return mpd
  end
end #class MPD

class Options
  attr_reader :verbose, :use_mpd, :pretend, :match, :items, :artists
  def initialize args
    @verbose = true
    @use_mpd = true
    @pretend = false
    @match = 50
    @items = 20
    @artists = []
    until args.empty?
      t = args.shift
      @verbose = false if t == "-s" or t == "--silent"
      @use_mpd = false if t == "-n" or t == "--no-mpd"
      @pretend = true if t == "-p" or t == "--pretend"
      @match = args.shift.to_i if t == "-m" or t == "--match"
      @items = args.shift.to_i if t == "-i" or t == "--items"
      @artists.push t unless t[0].chr == "-"
      if t == "-h" or t == "--help" or t == "-?"
        puts "some help would be realy nice..."
        exit 0
      end #help
    end
  end
end #class Options

$options = Options.new ARGV
#puts $options.to_yaml

mpd = MPD.new_connection if $options.use_mpd

if $options.artists.empty? and mpd
  song = mpd.current_song

  unless song
    $stderr.puts "currently not playing, please give an artist as argument"
    exit 1
  end

  #puts "#{song.artist} - #{song.title}"
  $options.artists.push song.artist
end

$options.artists.each do |artist_name | # quick and dirty :-/
artist = Scrobbler::Artist.new artist_name

# getting similar artists can take a little time
similar = artist.similar.select {|a| a.match.to_f > $options.match}
similar_artists = similar.collect {|a| a.name}

if $options.verbose
  puts "Similar Artists for #{artist_name}:"
  puts similar_artists
end

# continues with the next artist if no mpd invocation is planed
next unless $options.use_mpd

# reconnect if we lost meanwhile the connection
mpd.connect unless mpd.connected?

songs_by_artist = Hash.new

similar_artists.each do |a|
  songs = mpd.find "artist", a
  songs_by_artist[a] = songs unless songs.empty?
end

#puts songs_by_artist.to_yaml

if songs_by_artist.empty?
  puts "no similar artists found in your music-db"
  exit 0
end

songs_to_add = Array.new
# we have to get a new artist array because it can happen
# that no songs a found for a similar_artist
artists = songs_by_artist.keys

$options.items.times do
  artist = artists.random
  song = songs_by_artist[artist].random
  songs_to_add.push song
end

#puts songs_to_add.to_yaml

# reconnect if we lost meanwhile the connection
mpd.connect unless mpd.connected?

songs_to_add.each do |song|
  puts "adding #{song.artist} - #{song.title}" if $options.verbose
  mpd.add song.file unless $options.pretend
end
end # each artist
Music Player Command(1)                                Music Player Command(1)



NAME
       mpc - Program for controlling Music Player Daemon (MPD)

SYNOPSIS
       mpc [ ]

DESCRIPTION
       mpc is a client for MPD, the Music Player Daemon. mpc connects to a MPD
       running on a machine on the local network and controls MPD according to
       commands  and  arguments passed to it. If no arguments are passed, cur?
       rent status is given.


OPTIONS
       --format
              Configure  the  format  of  song  display  for  status  and  the
              playlist.   The  metadata  delimeters  are "%name%", "%artist%",
              "%album%", "%title%", "%track%", "%time%", and "%file%".  The []
              operator  is  used  to  group  output  such  that if no metadata
              delimeters are found or matched between ’[’ and ’]’,  then  none
              of  the  characters between ’[’ and ’]’ are output.  ’&’ and ’|’
              are logical operators for and and or.  ’#’  is  used  to  escape
              characters.   Some  useful examples for format are: "%file%" and
              "[
<?php
artist
% - ]%title
?>
|
<?php
file
?>
" --no-status Prevents the current song status from being printed on comple? tion of some of the commands. COMMANDS add Adds a song from the music database to the playlist. Can also read input from pipes. Use "mpc ls | mpc add" to add all files to the playlist. clear Empties playlist. crop Remove all songs except for the currently playing song. crossfade [] Gets and sets the current amount of crossfading between songs (0 disables crossfading). del Removes a song from the playlist. Can also read input from pipes. disable Disables the output, number is required. enable Enables the output, number is required. listall [] Lists from playlist. If no is specified, lists all songs. load Loads as playlist. ls [] Lists all files/folders in . If no is specified, lists all files in music directory. lsplaylists Lists available playlists. move Moves song at position to the postion in the playlist. next Starts playing next song on playlist. outputs Lists all available outputs pause Pauses playing. play Starts playing the song-number specified. If none is specified, plays number 1. playlist Prints entire playlist. prev Starts playing previous song. random Toggle random mode if state ("on" or "off") is not specified. repeat Toggle repeat mode if state ("on" or "off") is not specified. rm Deletes a specific playlist. save Saves playlist as . search Searches for songs that match the queries, where type is "artist", "album", "title", or "filename". seek [+-][] or <[+-]<0-100>%> Seeks by hour, minute or seconds, hours or minutes can be omit? ted. If seeking by percentage, seeks within the current song in the specified manner. If a "+" or "-" is used, the seek is done relative to the current song position. Absolute seeking by default. shuffle Shuffles all songs on the playlist. stats Displays statistics about MPD stop Stops playing. toggle Toggles between play and pause. If stopped starts playing. Does not support start playing at song number (use play). update [] Scans music directory for updates if no is specified. If one or more ’s are specified, scans only those path’s for updates. Can take input from a pipe. version Reports the version of MPD. volume [+-] Sets the volume to (0-100). If "+" or "-" is used, then it adjusts the volume relative to the current volume. ENVIRONMENT This section describes some environment variables that affect how mpc operates. MPD_HOST MPD_PORT By default, mpc connects to localhost:6600. This can be changed either at compile-time, or by exporting the MPD_HOST and MPD_PORT environment variables. To use a password with mpd, set MPD_HOST to pass? word@host. EXAMPLES Here is a script to load and play m3u playlists (useful for mozilla): #!/bin/bash mpc clear cat $1 | mpc add mpc play This script can be used to load and play pls playlists (again, useful for mozilla): #!/bin/bash mpc clear grep ’^File[0-9]*’ $1 | sed -e ’s/^File[0-9]*=//’ | mpc add mpc play BUGS Report bugs on http://www.musicpd.org/mantis/ NOTE Since MPD uses UTF-8, mpc needs to convert characters to the charset used by the local system. If you get character conversion errors when your running mpc you probably need to set up your locale. This is done by setting any of the LC_CTYPE, LANG or LC_ALL enviroment vatiables (LC_CTYPE only affects character handling). SEE ALSO mpd(1) AUTHOR See , for contributors to mpc Music Player Command(1) First off, I didn't write any of these scripts. Most are licenced GNU GPL, and the other are simple here for archive. See appended URL for credits and sources. Make sure you have MPC installed (aptitude -P install mpc)

mg (mpc grep)

From: http://www.musicpd.org/forum/index.php?topic=773.0 What it does is search through mpd's database, by filename, for whatever you give it. You don't have to quote anything either. mg also takes what you searched for and puts it into ~/.mg-lookup, which is used later to good effect. Example: mg Behind Blue Eyes
#!/bin/bash
mpc search filename "$*" | tee ~/.mg-lookup

ma (mpc add)

From: http://www.musicpd.org/forum/index.php?topic=773.0 This one has two modes of operation. If you just run it on command line without any arguments it will take all of the files found by the last 'mg' call (this is where ~/.mg-lookup comes in handy) and adds to the playlist. You can also use 'ma' with arguments. In that case, it will search through mpc's database just like mg would, except it will immediately add anything it finds to the playlist. This is useful if you're sure of what the search will return and want to cut out the middleman.
#!/bin/bash
if [ "$1" = "" ]; then
cat ~/.mg-lookup | mpc add
else
mpc search filename "$*" | mpc add
fi

mpg (mpc playlist grep)

From: http://www.musicpd.org/forum/index.php?topic=773.0 This will simply grep the current playlist for all arguments given to it. [coolcode lang="bash" download="mpg"]#!/bin/bash mpc playlist | grep -i "$*"[/coolcode]

mga (mpc grep albums)

From: http://www.musicpd.org/forum/index.php?topic=773.msg3553#msg3553 What it does is search through mpd's database, by album, for whatever you give it.
#!/bin/bash
mpc search filename "$*" | tee ~/.mg-lookup | awk -F/ '{print $2 " - "$3}' | uniq | sort

mhtml (mpc playlist 2 html)

Goto: http://www.musicpd.org/forum/index.php?topic=440.0

m3u 2 mpc

From: http://www.musicpd.org/forum/index.php?topic=287.msg1391#msg1391
#!/bin/sh
mpc clear
cat $1 | mpc add
mpc play

pls 2 mpc

From: http://www.musicpd.org/forum/index.php?topic=287.msg1391#msg1391
#!/bin/sh
mpc clear
grep '^File[0-9]*' $1 | sed -e 's/^File[0-9]*=//' | mpc add
mpc play

Tiny cached PHP "now playing" script

Goto: http://www.musicpd.org/forum/index.php?topic=939.msg4082#msg4082

Irssi MPD client

Goto: https://svn.musicpd.org/iMPD/trunk/iMPD.pl

Playlistbuilder

This is the BEST hack on this page... the mpc playlist is dull, no more! Simply get this script and run playlistbuilder and have your playlist filled with _simular_ songs. Oh, I've slightly modified this, added some instructions and changed up the playlist build. Still... The guy/gal who made this is WONDERFUL! Thanks. :-)
#! /usr/bin/env ruby

# required gems: scrobbler, librmpd

# Licence: GNU GPLv2
# Author: jonas@fs.ei.tum.de

## ABOUT PLAYLISTBUILDER
# http://mpd.wikia.com/wiki/Client:Playlistbuilder
#
# Get the artist of the current song, look up some similar artists,
# search your mpd-music for these artists and add 10 random songs of them to the playlist

#  playlistbuilder
#
# Look up your music for artists similar to the Arctic Monkeys and the Kaiser Chiefs
# and add 5 similar songs each

#  playlistbuilder -i 5 "arctic monkeys" "kaiser chiefs"
#
# Use the -p (--pretend) switch to do all but the actual appending.
# Use the -m (--match) to give an other match-level
#  (default 90, lower means the artist is less similar but you may got more matches within your music).
# Use -s (--silent) to supress non-error output.
# With -n (--no-mpd) you can disable the MPD-interaction and only see the list of similar artists.

## INSTALLATION
# wget https://trac.fs.ei.tum.de/musik/browser/mpd/playlistbuilder/playlistbuil...
#
# wget http://rubyforge.org/frs/download.php/15722/librmpd-0.1.1.gem
# sudo gem install librmpd-0.1.1.gm
#
# sudo gem install scrobbler
#

require "rubygems"
require "scrobbler"
require "librmpd"

class Array
  def random
    # implement a sort of random-choice
    self[rand(self.length)]
  end
end

class MPD
  def self.new_connection
    host = ( ENV['MPD_HOST'] or 'localhost' )
    port = ( ENV['MPD_PORT'] or 6600 )
    mpd = self.new host, port
    try = 0
    begin
      puts "connecting to #{host}:#{port}..." if $options.verbose
      mpd.connect
    rescue RuntimeError
      try += 1
      unless try > 3
         $stderr.puts "connection failed on #{try}. attempt, retrying..."
         retry
      else
         $stderr.puts "unable to connect"
         exit 1
      end
    end
    return mpd
  end
end #class MPD

class Options
  attr_reader :verbose, :use_mpd, :pretend, :match, :items, :artists
  def initialize args
    @verbose = true
    @use_mpd = true
    @pretend = false
    @match = 50
    @items = 20
    @artists = []
    until args.empty?
      t = args.shift
      @verbose = false if t == "-s" or t == "--silent"
      @use_mpd = false if t == "-n" or t == "--no-mpd"
      @pretend = true if t == "-p" or t == "--pretend"
      @match = args.shift.to_i if t == "-m" or t == "--match"
      @items = args.shift.to_i if t == "-i" or t == "--items"
      @artists.push t unless t[0].chr == "-"
      if t == "-h" or t == "--help" or t == "-?"
        puts "some help would be realy nice..."
        exit 0
      end #help
    end
  end
end #class Options

$options = Options.new ARGV
#puts $options.to_yaml

mpd = MPD.new_connection if $options.use_mpd

if $options.artists.empty? and mpd
  song = mpd.current_song

  unless song
    $stderr.puts "currently not playing, please give an artist as argument"
    exit 1
  end

  #puts "#{song.artist} - #{song.title}"
  $options.artists.push song.artist
end

$options.artists.each do |artist_name | # quick and dirty :-/
artist = Scrobbler::Artist.new artist_name

# getting similar artists can take a little time
similar = artist.similar.select {|a| a.match.to_f > $options.match}
similar_artists = similar.collect {|a| a.name}

if $options.verbose
  puts "Similar Artists for #{artist_name}:"
  puts similar_artists
end

# continues with the next artist if no mpd invocation is planed
next unless $options.use_mpd

# reconnect if we lost meanwhile the connection
mpd.connect unless mpd.connected?

songs_by_artist = Hash.new

similar_artists.each do |a|
  songs = mpd.find "artist", a
  songs_by_artist[a] = songs unless songs.empty?
end

#puts songs_by_artist.to_yaml

if songs_by_artist.empty?
  puts "no similar artists found in your music-db"
  exit 0
end

songs_to_add = Array.new
# we have to get a new artist array because it can happen
# that no songs a found for a similar_artist
artists = songs_by_artist.keys

$options.items.times do
  artist = artists.random
  song = songs_by_artist[artist].random
  songs_to_add.push song
end

#puts songs_to_add.to_yaml

# reconnect if we lost meanwhile the connection
mpd.connect unless mpd.connected?

songs_to_add.each do |song|
  puts "adding #{song.artist} - #{song.title}" if $options.verbose
  mpd.add song.file unless $options.pretend
end
end # each artist

Tags