2 # This program is free software; you can redistribute it and/or modify
3 # it under the terms of the GNU General Public License as published by
4 # the Free Software Foundation; either version 2 of the License, or
5 # (at your option) any later version.
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
12 # You should have received a copy of the GNU General Public License
13 # along with this program; if not, write to the Free Software
14 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 use Audio
::MPD
::Collection
;
25 use Audio
::MPD
::Status
;
30 use base qw
[ Class
::Accessor
::Fast
];
31 __PACKAGE__
->mk_accessors( qw
[ _host _password _port collection version
] );
34 our $VERSION = '0.16.2';
41 # my $mpd = Audio::MPD->new( [$hostname], [$port], [$password] )
43 # This is the constructor for Audio::MPD. One can specify a $hostname, a
44 # $port, and a $password.
45 # If none is specified then defaults to environment vars MPD_HOST, MPD_PORT
46 # and MPD_PASSWORD. If those aren't set, defaults to 'localhost', 6600 and ''.
50 my ($host, $port, $password) = @_;
53 $host = $ENV{MPD_HOST
} || 'localhost' unless defined $host;
54 $port = $ENV{MPD_PORT
} || '6600' unless defined $port;
55 $password = $ENV{MPD_PASSWORD
} || '' unless defined $password;
57 # create & bless the object.
61 _password
=> $password,
65 # create the collection object and store it.
66 $self->collection( Audio
::MPD
::Collection
->new($self) );
68 # try to issue a ping to test connection - this can die.
80 # my @result = $mpd->_send_command( $command );
82 # This method is central to the module. It is responsible for interacting with
83 # mpd by sending the $command and reading output - that will be returned as an
84 # array of chomped lines (status line will not be returned).
86 # Note that currently, this method will connect to mpd before sending any
87 # command, and will disconnect after the command has been issued. This scheme
88 # is far from optimal, but allows us not to care about timeout disconnections.
90 # /!\ Note that we're using high-level, blocking sockets. This means that if
91 # the mpd server is slow, or hangs for whatever reason, or even crash abruptly,
92 # the program will be hung forever in this sub. The POE::Component::Client::MPD
93 # module is way safer - you're advised to use it instead of Audio::MPD.
95 # This method can die on several conditions:
96 # - if the server cannot be reached,
97 # - if it's not an mpd server,
98 # - if the password is incorrect,
99 # - or if the command is an invalid mpd command.
100 # In the latter case, the mpd error message will be returned.
103 my ($self, $command) = @_;
105 # try to connect to mpd.
106 my $socket = IO
::Socket
::INET
->new(
107 PeerAddr
=> $self->_host,
108 PeerPort
=> $self->_port
110 or die "Could not create socket: $!\n";
113 # parse version information.
114 $line = $socket->getline;
116 die "Not a mpd server - welcome string was: [$line]\n"
117 if $line !~ /^OK MPD (.+)$/;
121 if ( $self->_password ) {
122 $socket->print( 'password ' . encode
('utf-8', $self->_password) . "\n" );
123 $line = $socket->getline;
124 die $line if $line =~ s/^ACK //;
127 # ok, now we're connected - let's issue the command.
128 $socket->print( encode
('utf-8', $command) );
130 while (defined ( $line = $socket->getline ) ) {
132 die $line if $line =~ s/^ACK //; # oops - error.
133 last if $line =~ /^OK/; # end of output.
134 push @output, decode
('utf-8', $line);
145 # my @items = $mpd->_cooked_command_as_items( $command );
147 # Lots of Audio::MPD methods are using _send_command() and then parse the
148 # output as a collection of Audio::MPD::Item. This method is meant to
149 # factorize this code, and will parse the raw output of _send_command() in
150 # a cooked list of items.
152 sub _cooked_command_as_items
{
153 my ($self, $command) = @_;
155 my @lines = $self->_send_command($command);
158 # parse lines in reverse order since "file:" or "directory:" lines
159 # come first. therefore, let's first store every other parameter,
160 # and the last line will trigger the object creation.
161 # of course, since we want to preserve the playlist order, this means
162 # that we're going to unshift the objects instead of push.
163 foreach my $line (reverse @lines) {
164 my ($k,$v) = split /:\s+/, $line, 2;
166 next unless $k eq 'file' || $k eq 'directory'; # last param of item
167 unshift @items, Audio
::MPD
::Item
->new(%param);
176 # my @list = $mpd->_cooked_command_strip_first_field( $command );
178 # Lots of Audio::MPD methods are using _send_command() and then parse the
179 # output to remove the first field (with the colon ":" acting as separator).
180 # This method is meant to factorize this code, and will parse the raw output
181 # of _send_command() in a cooked list of strings.
183 sub _cooked_command_strip_first_field
{
184 my ($self, $command) = @_;
187 map { ( split(/:\s+/, $_, 2) )[1] }
188 $self->_send_command($command);
196 # -- MPD interaction: general commands
201 # Sends a ping command to the mpd server.
205 $self->_send_command( "ping\n" );
210 # my $version = $mpd->version;
212 # Return version of MPD server's connected.
214 # sub version {} # implemented as an accessor.
221 # Send a message to the MPD server telling it to shut down.
225 $self->_send_command("kill\n");
230 # $mpd->password( [$password] )
232 # Change password used to communicate with MPD server to $password.
233 # Empty string is assumed if $password is not supplied.
236 my ($self, $passwd) = @_;
238 $self->_password($passwd);
239 $self->ping; # ping sends a command, and thus the password is sent
244 # $mpd->updatedb( [$path] );
246 # Force mpd to recan its collection. If $path (relative to MPD's music
247 # directory) is supplied, MPD will only scan it - otherwise, MPD will rescan
248 # its whole collection.
251 my ($self, $path) = @_;
253 $self->_send_command("update $path\n");
258 # my @handlers = $mpd->urlhandlers;
260 # Return an array of supported URL schemes.
264 return $self->_cooked_command_strip_first_field("urlhandlers\n");
268 # -- MPD interaction: handling volume & output
271 # $mpd->volume( [+][-]$volume );
273 # Sets the audio output volume percentage to absolute $volume.
274 # If $volume is prefixed by '+' or '-' then the volume is changed relatively
278 my ($self, $volume) = @_;
280 if ($volume =~ /^(-|\+)(\d+)/ ) {
281 my $current = $self->status->volume;
282 $volume = $1 eq '+' ?
$current + $2 : $current - $2;
284 $self->_send_command("setvol $volume\n");
289 # $mpd->output_enable( $output );
291 # Enable the specified audio output. $output is the ID of the audio output.
294 my ($self, $output) = @_;
295 $self->_send_command("enableoutput $output\n");
300 # $mpd->output_disable( $output );
302 # Disable the specified audio output. $output is the ID of the audio output.
305 my ($self, $output) = @_;
306 $self->_send_command("disableoutput $output\n");
311 # -- MPD interaction: retrieving info from current state
316 # Return a hashref with the number of artists, albums, songs in the database,
317 # as well as mpd uptime, the playtime of the playlist / the database and the
318 # last update of the database.
323 map { my ($k,$v) = split(/:\s+/, $_, 2); ($k => $v) }
324 $self->_send_command( "stats\n" );
330 # my $status = $mpd->status;
332 # Return an Audio::MPD::Status object with various information on current
333 # MPD server settings. Check the embedded pod for more information on the
334 # available accessors.
338 my @output = $self->_send_command( "status\n" );
339 my $status = Audio
::MPD
::Status
->new( @output );
345 # my $list = $mpd->playlist;
347 # Return an arrayref of C<Audio::MPD::Item::Song>s, one for each of the
348 # songs in the current playlist.
353 my @list = $self->_cooked_command_as_items("playlistinfo\n");
359 # my $list = $mpd->pl_changes( $plversion );
361 # Return a list with all the songs (as API::Song objects) added to
362 # the playlist since playlist $plversion.
365 my ($self, $plid) = @_;
367 return $self->_cooked_command_as_items("plchanges $plid\n");
372 # my $song = $mpd->current;
374 # Return an C<Audio::MPD::Item::Song> representing the song currently playing.
378 my ($item) = $self->_cooked_command_as_items("currentsong\n");
384 # my $song = $mpd->song( [$song] )
386 # Return an C<Audio::MPD::Item::Song> representing the song number C<$song>.
387 # If C<$song> is not supplied, returns the current song.
390 my ($self, $song) = @_;
391 return $self->current unless defined $song;
392 my ($item) = $self->_cooked_command_as_items("playlistinfo $song\n");
398 # my $song = $mpd->songid( [$songid] )
400 # Return an C<Audio::MPD::Item::Song> representing the song with id C<$songid>.
401 # If C<$songid> is not supplied, returns the current song.
404 my ($self, $songid) = @_;
405 return $self->current unless defined $songid;
406 my ($item) = $self->_cooked_command_as_items("playlistid $songid\n");
411 # -- MPD interaction: altering settings
414 # $mpd->repeat( [$repeat] );
416 # Set the repeat mode to $repeat (1 or 0). If $repeat is not specified then
417 # the repeat mode is toggled.
420 my ($self, $mode) = @_;
422 $mode = not $self->status->repeat
423 unless defined $mode; # toggle if no param
424 $mode = $mode ?
1 : 0; # force integer
425 $self->_send_command("repeat $mode\n");
430 # $mpd->random( [$random] );
432 # Set the random mode to $random (1 or 0). If $random is not specified then
433 # the random mode is toggled.
436 my ($self, $mode) = @_;
438 $mode = not $self->status->random
439 unless defined $mode; # toggle if no param
440 $mode = $mode ?
1 : 0; # force integer
441 $self->_send_command("random $mode\n");
446 # $mpd->fade( [$seconds] );
448 # Enable crossfading and set the duration of crossfade between songs. If
449 # $seconds is not specified or $seconds is 0, then crossfading is disabled.
452 my ($self, $value) = @_;
454 $self->_send_command("crossfade $value\n");
458 # -- MPD interaction: controlling playback
461 # $mpd->play( [$song] );
463 # Begin playing playlist at song number $song. If no argument supplied,
467 my ($self, $number) = @_;
468 $number = '' unless defined $number;
469 $self->_send_command("play $number\n");
473 # $mpd->playid( [$songid] );
475 # Begin playing playlist at song ID $songid. If no argument supplied,
479 my ($self, $number) = @_;
481 $self->_send_command("playid $number\n");
486 # $mpd->pause( [$sate] );
488 # Pause playback. If $state is 0 then the current track is unpaused, if
489 # $state is 1 then the current track is paused.
491 # Note that if $state is not given, pause state will be toggled.
494 my ($self, $state) = @_;
495 $state ||= ''; # default is to toggle
496 $self->_send_command("pause $state\n");
507 $self->_send_command("stop\n");
514 # Play next song in playlist.
518 $self->_send_command("next\n");
524 # Play previous song in playlist.
528 $self->_send_command("previous\n");
533 # $mpd->seek( $time, [$song]);
535 # Seek to $time seconds in song number $song. If $song number is not specified
536 # then the perl module will try and seek to $time in the current song.
539 my ($self, $time, $song) = @_;
540 $time ||= 0; $time = int $time;
541 $song = $self->status->song if not defined $song; # seek in current song
542 $self->_send_command( "seek $song $time\n" );
547 # $mpd->seekid( $time, $songid );
549 # Seek to $time seconds in song ID $songid. If $song number is not specified
550 # then the perl module will try and seek to $time in the current song.
553 my ($self, $time, $song) = @_;
554 $time ||= 0; $time = int $time;
555 $song = $self->status->songid if not defined $song; # seek in current song
556 $self->_send_command( "seekid $song $time\n" );
560 # -- MPD interaction: handling playlist
563 # $mpd->add( $path );
565 # Add the song identified by $path (relative to MPD's music directory) to
566 # the current playlist. No return value.
569 my ($self, $path) = @_;
570 $self->_send_command( qq[add
"$path"\n] );
575 # $mpd->delete( $song [, $song [...] ] );
577 # Remove song number $song from the current playlist. No return value.
580 my ($self, @songs) = @_;
582 "command_list_begin\n"
583 . join( '', map { "delete $_\n" } @songs )
584 . "command_list_end\n";
585 $self->_send_command( $command );
590 # $mpd->deleteid( $songid [, $songid [...] ]);
592 # Remove the specified $songid from the current playlist. No return value.
595 my ($self, @songs) = @_;
597 "command_list_begin\n"
598 . join( '', map { "deleteid $_\n" } @songs )
599 . "command_list_end\n";
600 $self->_send_command( $command );
607 # Remove all the songs from the current playlist. No return value.
611 $self->_send_command("clear\n");
618 # Remove all of the songs from the current playlist *except* the current one.
623 my $status = $self->status;
624 my $cur = $status->song;
625 my $len = $status->playlistlength - 1;
628 "command_list_begin\n"
629 . join( '', map { $_ != $cur ?
"delete $_\n" : '' } reverse 0..$len )
630 . "command_list_end\n";
631 $self->_send_command( $command );
637 my ($self, $from, $to) = @_;
638 $self->_send_command("swap $from $to\n");
642 my ($self, $from, $to) = @_;
643 $self->_send_command("swapid $from $to\n");
648 $self->_send_command("shuffle\n");
652 my ($self, $song, $pos) = @_;
653 $self->_send_command("move $song $pos\n");
657 my ($self, $song, $pos) = @_;
658 $self->_send_command("moveid $song $pos\n");
662 my ($self, $playlist) = @_;
663 return unless defined $playlist;
664 $self->_send_command( qq[load
"$playlist"\n] );
668 my ($self, $playlist) = @_;
669 return unless defined $playlist;
670 $self->_send_command( qq[save
"$playlist"\n] );
674 if(!$self->_process_feedback)
676 # Does the playlist already exist?
677 if(${$self->get_error}[0] eq '56' && $config{'OVERWRITE_PLAYLIST'})
679 $self->rm($playlist);
680 $self->save($playlist);
693 my ($self, $playlist) = @_;
694 return unless defined $playlist;
695 $self->_send_command( qq[rm
"$playlist"\n] );
700 ###############################################################
702 #-------------------------------------------------------------#
703 # This section contains all methods not directly accessing #
704 # MPD, but may be useful for most people using the module. #
705 ###############################################################
708 sub get_time_format
{
711 # Get the time from MPD; example: 49:395 (seconds so far:total seconds)
712 my ($sofar, $total) = split /:/, $self->status->time;
713 return sprintf "%d:%02d/%d:%02d",
714 ($sofar / 60), # minutes so far
715 ($sofar % 60), # seconds - minutes so far
716 ($total / 60), # minutes total
717 ($total % 60);# seconds - minutes total
723 # Get the time from MPD; example: 49:395 (seconds so far:total seconds)
724 my ($sofar, $total) = split /:/, $self->status->time;
725 my $left = $total - $sofar;
727 # Store seconds for everything
729 $rv->{seconds_so_far
} = $sofar;
730 $rv->{seconds_total
} = $total;
731 $rv->{seconds_left
} = $left;
733 # Store the percentage; use one decimal point
736 ?
100*$rv->{seconds_so_far
}/$rv->{seconds_total
}
738 $rv->{percentage
} = sprintf "%.1f",$rv->{percentage
};
741 # Parse the time so far
742 my $min_so_far = ($sofar / 60);
743 my $sec_so_far = ($sofar % 60);
745 $rv->{time_so_far
} = sprintf("%d:%02d", $min_so_far, $sec_so_far);
746 $rv->{minutes_so_far
} = sprintf("%00d", $min_so_far);
747 $rv->{seconds_so_far
} = sprintf("%00d", $sec_so_far);
750 # Parse the total time
751 my $min_tot = ($total / 60);
752 my $sec_tot = ($total % 60);
754 $rv->{time_total
} = sprintf("%d:%02d", $min_tot, $sec_tot);
755 $rv->{minutes
} = $min_tot;
756 $rv->{seconds
} = $sec_tot;
758 # Parse the time left
759 my $min_left = ($left / 60);
760 my $sec_left = ($left % 60);
761 $rv->{time_left
} = sprintf("-%d:%02d", $min_left, $sec_left);
777 Audio::MPD - Class for talking to MPD (Music Player Daemon) servers
784 my $mpd = Audio::MPD->new();
792 Audio::MPD gives a clear object-oriented interface for talking to and
793 controlling MPD (Music Player Daemon) servers. A connection to the MPD
794 server is established as soon as a new Audio::MPD object is created.
795 Commands are then sent to the server as the class's methods are called.
804 =item new( [$host] [, $port] [, $password] )
806 This is the constructor for Audio::MPD. One can specify a $hostname, a
807 $port, and a $password.
809 If none is specified then defaults to environment vars MPD_HOST, MPD_PORT
810 and MPD_PASSWORD. If those aren't set, defaults to 'localhost', 6600 and ''.
815 =head2 Controlling the server
821 Sends a ping command to the mpd server.
824 =item $mpd->version()
826 Return the version number for the server we are connected to.
831 Send a message to the MPD server telling it to shut down.
834 =item $mpd->password( [$password] )
836 Change password used to communicate with MPD server to $password.
837 Empty string is assumed if $password is not supplied.
840 =item $mpd->updatedb( [$path] )
842 Force mpd to recan its collection. If $path (relative to MPD's music directory)
843 is supplied, MPD will only scan it - otherwise, MPD will rescan its whole
847 =item $mpd->urlhandlers()
849 Return an array of supported URL schemes.
855 =head2 Handling volume & output
859 =item $mpd->volume( [+][-]$volume )
861 Sets the audio output volume percentage to absolute $volume.
862 If $volume is prefixed by '+' or '-' then the volume is changed relatively
866 =item $mpd->output_enable( $output )
868 Enable the specified audio output. $output is the ID of the audio output.
871 =item $mpd->output_disable( $output )
873 Disable the specified audio output. $output is the ID of the audio output.
878 =head2 Retrieving info from current state
884 Return a hashref with the number of artists, albums, songs in the database,
885 as well as mpd uptime, the playtime of the playlist / the database and the
886 last update of the database
891 Return an C<Audio::MPD::Status> object with various information on current
892 MPD server settings. Check the embedded pod for more information on the
896 =item $mpd->playlist( )
898 Return an arrayref of C<Audio::MPD::Item::Song>s, one for each of the
899 songs in the current playlist.
902 =item $mpd->pl_changes( $plversion )
904 Return a list with all the songs (as API::Song objects) added to
905 the playlist since playlist $plversion.
908 =item $mpd->current( )
910 Return an C<Audio::MPD::Item::Song> representing the song currently playing.
913 =item $mpd->song( [$song] )
915 Return an C<Audio::MPD::Item::Song> representing the song number C<$song>. If
916 C<$song> is not supplied, returns the current song.
919 =item $mpd->songid( [$songid] )
921 Return an C<Audio::MPD::Item::Song> representing the song with id C<$songid>.
922 If C<$songid> is not supplied, returns the current song.
927 =head2 Altering MPD settings
931 =item $mpd->repeat( [$repeat] )
933 Set the repeat mode to $repeat (1 or 0). If $repeat is not specified then
934 the repeat mode is toggled.
937 =item $mpd->random( [$random] )
939 Set the random mode to $random (1 or 0). If $random is not specified then
940 the random mode is toggled.
943 =item $mpd->fade( [$seconds] )
945 Enable crossfading and set the duration of crossfade between songs.
946 If $seconds is not specified or $seconds is 0, then crossfading is disabled.
951 =head2 Controlling playback
955 =item $mpd->play( [$song] )
957 Begin playing playlist at song number $song. If no argument supplied,
961 =item $mpd->playid( [$songid] )
963 Begin playing playlist at song ID $songid. If no argument supplied,
967 =item $mpd->pause( [$state] )
969 Pause playback. If C<$state> is 0 then the current track is unpaused,
970 if $state is 1 then the current track is paused.
972 Note that if C<$state> is not given, pause state will be toggled.
982 Play next song in playlist.
987 Play previous song in playlist.
990 =item $mpd->seek( $time, [$song])
992 Seek to $time seconds in song number $song. If $song number is not specified
993 then the perl module will try and seek to $time in the current song.
996 =item $mpd->seekid( $time, $songid )
998 Seek to $time seconds in song ID $songid. If $song number is not specified
999 then the perl module will try and seek to $time in the current song.
1004 =head2 Handling playlist
1008 =item $mpd->add( $path )
1010 Add the song identified by $path (relative to MPD's music directory) to the
1011 current playlist. No return value.
1014 =item $mpd->delete( $song )
1016 Remove song number $song from the current playlist. No return value.
1019 =item $mpd->deleteid( $songid )
1021 Remove the specified $songid from the current playlist. No return value.
1026 Remove all the songs from the current playlist. No return value.
1031 Remove all of the songs from the current playlist *except* the
1032 song currently playing.
1035 =item $mpd->swap( $song1, $song2 )
1037 Swap positions of song number $song1 and $song2 on the current playlist. No
1041 =item $mpd->swapid( $songid1, $songid2 )
1043 Swap the postions of song ID $songid1 with song ID $songid2 on the current
1044 playlist. No return value.
1047 =item $mpd->move( $song, $newpos )
1049 Move song number $song to the position $newpos. No return value.
1052 =item $mpd->moveid( $songid, $newpos )
1054 Move song ID $songid to the position $newpos. No return value.
1057 =item $mpd->shuffle()
1059 Shuffle the current playlist. No return value.
1062 =item $mpd->load( $playlist )
1064 Load list of songs from specified $playlist file. No return value.
1067 =item $mpd->save( $playlist )
1069 Save the current playlist to a file called $playlist in MPD's playlist
1070 directory. No return value.
1073 =item $mpd->rm( $playlist )
1075 Delete playlist named $playlist from MPD's playlist directory. No return value.
1080 =head2 Retrieving information from current playlist
1084 =item $mpd->get_time_format( )
1086 Returns the current position and duration of the current song.
1087 String is formatted at "M:SS/M:SS", with current time first and total time
1091 =item $mpd->get_time_info( )
1093 Return current timing information in various different formats
1094 contained in a hashref with the following keys:
1098 =item minutes_so_far
1100 =item seconds_so_far
1123 =head2 Searching the collection
1125 To search the collection, use the C<collection()> accessor, returning the
1126 associated C<Audio::MPD::Collection> object. You will then be able to call:
1128 $mpd->collection->random_song();
1130 See C<Audio::MPD::Collection> documentation for more details on available
1136 You can find more information on the mpd project on its homepage at
1137 L<http://www.musicpd.org>, or its wiki L<http://mpd.wikia.com>.
1139 Regarding this Perl module, you can report bugs on CPAN via
1140 L<http://rt.cpan.org/Public/Bug/Report.html?Queue=Audio-MPD>.
1142 Audio::MPD development takes place on <audio-mpd@googlegroups.com>: feel free
1143 to join us. (use L<http://groups.google.com/group/audio-mpd> to sign in). Our
1144 subversion repository is located at L<https://svn.musicpd.org>.
1150 Jerome Quelin <jquelin@cpan.org>
1152 Original code by Tue Abrahamsen <tue.abrahamsen@gmail.com>, documented by
1153 Nicholas J. Humfrey <njh@aelius.com>.
1157 =head1 COPYRIGHT AND LICENSE
1159 Copyright (c) 2005 Tue Abrahamsen <tue.abrahamsen@gmail.com>
1161 Copyright (c) 2006 Nicholas J. Humfrey <njh@aelius.com>
1163 Copyright (c) 2007 Jerome Quelin <jquelin@cpan.org>
1166 This program is free software; you can redistribute it and/or modify
1167 it under the terms of the GNU General Public License as published by
1168 the Free Software Foundation; either version 2 of the License, or
1169 (at your option) any later version.
1171 This program is distributed in the hope that it will be useful,
1172 but WITHOUT ANY WARRANTY; without even the implied warranty of
1173 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1174 GNU General Public License for more details.