2 # This file is part of Audio::MPD
3 # Copyright (c) 2007-2009 Jerome Quelin, all rights reserved.
5 # This program is free software; you can redistribute it and/or modify
6 # it under the same terms as Perl itself.
15 use Audio
::MPD
::Collection
;
16 use Audio
::MPD
::Common
::Item
;
17 use Audio
::MPD
::Common
::Stats
;
18 use Audio
::MPD
::Common
::Status
;
19 use Audio
::MPD
::Playlist
;
25 use base qw
[ Class
::Accessor
::Fast Exporter
];
26 __PACKAGE__
->mk_accessors(
27 qw
[ _conntype _host _password _port _socket
28 collection playlist version
] );
31 our $VERSION = '0.19.6';
33 Readonly
our $REUSE => 0;
34 Readonly
our $ONCE => 1;
36 our @EXPORT = qw
[ $REUSE $ONCE ];
43 # my $mpd = Audio::MPD->new( [%opts] )
45 # This is the constructor for Audio::MPD. One can specify the following
47 # - host => $hostname : defaults to environment var MPD_HOST, then to 'localhost'
48 # - port => $port : defaults to env var MPD_PORT, then to 6600
49 # - password => $password : defaults to env var MPD_PASSWORD, then to ''
50 # - conntype => $type : how the connection to mpd server is handled. it can be
51 # either $REUSE: reuse the same connection
52 # or $ONCE: open a new connection per command (default)
55 my ($class, %opts) = @_;
58 my ($default_password, $default_host) = split( '@', $ENV{MPD_HOST
} )
59 if exists $ENV{MPD_HOST
} && $ENV{MPD_HOST
} =~ /@/;
60 my $host = $opts{host
} || $default_host || $ENV{MPD_HOST
} || 'localhost';
61 my $port = $opts{port
} || $ENV{MPD_PORT
} || '6600';
62 my $password = $opts{password
} || $ENV{MPD_PASSWORD
} || $default_password || '';
64 # create & bless the object.
68 _password
=> $password,
69 _conntype
=> exists $opts{conntype
} ?
$opts{conntype
} : $ONCE,
73 # create the connection if conntype is set to $REUSE
74 $self->_connect_to_mpd_server if $self->_conntype == $REUSE;
77 # create the helper objects and store them.
78 $self->collection( Audio
::MPD
::Collection
->new($self) );
79 $self->playlist ( Audio
::MPD
::Playlist
->new($self) );
81 # try to issue a ping to test connection - this can die.
93 # $mpd->_connect_to_mpd_server;
95 # This method connects to the mpd server. It can die on several conditions:
96 # - if the server cannot be reached,
97 # - if it's not an mpd server,
98 # - or if the password is incorrect,
100 sub _connect_to_mpd_server
{
103 # try to connect to mpd.
104 my $socket = IO
::Socket
::INET
->new(
105 PeerAddr
=> $self->_host,
106 PeerPort
=> $self->_port,
108 or die "Could not create socket: $!\n";
110 # parse version information.
111 my $line = $socket->getline;
113 die "Not a mpd server - welcome string was: [$line]\n"
114 if $line !~ /^OK MPD (.+)$/;
118 if ( $self->_password ) {
119 $socket->print( 'password ' . encode
('utf-8', $self->_password) . "\n" );
120 $line = $socket->getline;
121 die $line if $line =~ s/^ACK //;
125 $self->_socket($socket);
130 # my @result = $mpd->_send_command( $command );
132 # This method is central to the module. It is responsible for interacting with
133 # mpd by sending the $command and reading output - that will be returned as an
134 # array of chomped lines (status line will not be returned).
136 # This method can die on several conditions:
137 # - if the server cannot be reached,
138 # - if it's not an mpd server,
139 # - if the password is incorrect,
140 # - or if the command is an invalid mpd command.
141 # In the latter case, the mpd error message will be returned.
144 my ($self, $command) = @_;
146 $self->_connect_to_mpd_server if $self->_conntype == $ONCE;
147 my $socket = $self->_socket;
149 # ok, now we're connected - let's issue the command.
150 $socket->print( encode
('utf-8', $command) );
152 while (defined ( my $line = $socket->getline ) ) {
154 die $line if $line =~ s/^ACK //; # oops - error.
155 last if $line =~ /^OK/; # end of output.
156 push @output, decode
('utf-8', $line);
160 $socket->close if $self->_conntype == $ONCE;
167 # my @items = $mpd->_cooked_command_as_items( $command );
169 # Lots of Audio::MPD methods are using _send_command() and then parse the
170 # output as a collection of AMC::Item. This method is meant to factorize
171 # this code, and will parse the raw output of _send_command() in a cooked
174 sub _cooked_command_as_items
{
175 my ($self, $command) = @_;
177 my @lines = $self->_send_command($command);
180 # parse lines in reverse order since "file:" or "directory:" lines
181 # come first. therefore, let's first store every other parameter,
182 # and the last line will trigger the object creation.
183 # of course, since we want to preserve the playlist order, this means
184 # that we're going to unshift the objects instead of push.
185 foreach my $line (reverse @lines) {
186 my ($k,$v) = split /:\s/, $line, 2;
188 next unless $k eq 'file' || $k eq 'directory' || $k eq 'playlist'; # last param of item
189 unshift @items, Audio
::MPD
::Common
::Item
->new(%param);
198 # my %hash = $mpd->_cooked_command_as_kv( $command );
200 # Lots of Audio::MPD methods are using _send_command() and then parse the
201 # output to get a list of key / value (with the colon ":" acting as separator).
202 # This method is meant to factorize this code, and will parse the raw output
203 # of _send_command() in a cooked hash.
205 sub _cooked_command_as_kv
{
206 my ($self, $command) = @_;
208 map { split(/:\s/, $_, 2) }
209 $self->_send_command($command);
214 # my @list = $mpd->_cooked_command_strip_first_field( $command );
216 # Lots of Audio::MPD methods are using _send_command() and then parse the
217 # output to remove the first field (with the colon ":" acting as separator).
218 # This method is meant to factorize this code, and will parse the raw output
219 # of _send_command() in a cooked list of strings.
221 sub _cooked_command_strip_first_field
{
222 my ($self, $command) = @_;
225 map { ( split(/:\s+/, $_, 2) )[1] }
226 $self->_send_command($command);
234 # -- MPD interaction: general commands
239 # Sends a ping command to the mpd server.
243 $self->_send_command( "ping\n" );
248 # my $version = $mpd->version;
250 # Return version of MPD server's connected.
252 # sub version {} # implemented as an accessor.
259 # Send a message to the MPD server telling it to shut down.
263 $self->_send_command("kill\n");
268 # $mpd->password( [$password] )
270 # Change password used to communicate with MPD server to $password.
271 # Empty string is assumed if $password is not supplied.
274 my ($self, $passwd) = @_;
276 $self->_password($passwd);
277 $self->ping; # ping sends a command, and thus the password is sent
282 # $mpd->updatedb( [$path] );
284 # Force mpd to rescan its collection. If $path (relative to MPD's music
285 # directory) is supplied, MPD will only scan it - otherwise, MPD will rescan
286 # its whole collection.
289 my ($self, $path) = @_;
291 $self->_send_command("update $path\n");
296 # my @handlers = $mpd->urlhandlers;
298 # Return an array of supported URL schemes.
302 return $self->_cooked_command_strip_first_field("urlhandlers\n");
306 # -- MPD interaction: handling volume & output
309 # $mpd->volume( [+][-]$volume );
311 # Sets the audio output volume percentage to absolute $volume.
312 # If $volume is prefixed by '+' or '-' then the volume is changed relatively
316 my ($self, $volume) = @_;
318 if ($volume =~ /^(-|\+)(\d+)/ ) {
319 my $current = $self->status->volume;
320 $volume = $1 eq '+' ?
$current + $2 : $current - $2;
322 $self->_send_command("setvol $volume\n");
327 # $mpd->output_enable( $output );
329 # Enable the specified audio output. $output is the ID of the audio output.
332 my ($self, $output) = @_;
333 $self->_send_command("enableoutput $output\n");
338 # $mpd->output_disable( $output );
340 # Disable the specified audio output. $output is the ID of the audio output.
343 my ($self, $output) = @_;
344 $self->_send_command("disableoutput $output\n");
349 # -- MPD interaction: retrieving info from current state
354 # Return an AMC::Stats object with the current statistics of MPD.
358 my %kv = $self->_cooked_command_as_kv( "stats\n" );
359 return Audio
::MPD
::Common
::Stats
->new(\
%kv);
364 # my $status = $mpd->status;
366 # Return an AMC::Status object with various information on current
367 # MPD server settings. Check the embedded pod for more information on the
368 # available accessors.
372 my %kv = $self->_cooked_command_as_kv( "status\n" );
373 my $status = Audio
::MPD
::Common
::Status
->new( \
%kv );
379 # my $song = $mpd->current;
381 # Return an AMC::Item::Song representing the song currently playing.
385 my ($item) = $self->_cooked_command_as_items("currentsong\n");
391 # my $song = $mpd->song( [$song] )
393 # Return an AMC::Item::Song representing the song number $song.
394 # If $song is not supplied, returns the current song.
397 my ($self, $song) = @_;
398 return $self->current unless defined $song;
399 my ($item) = $self->_cooked_command_as_items("playlistinfo $song\n");
405 # my $song = $mpd->songid( [$songid] )
407 # Return an AMC::Item::Song representing the song with id $songid.
408 # If $songid is not supplied, returns the current song.
411 my ($self, $songid) = @_;
412 return $self->current unless defined $songid;
413 my ($item) = $self->_cooked_command_as_items("playlistid $songid\n");
418 # -- MPD interaction: altering settings
421 # $mpd->repeat( [$repeat] );
423 # Set the repeat mode to $repeat (1 or 0). If $repeat is not specified then
424 # the repeat mode is toggled.
427 my ($self, $mode) = @_;
429 $mode = not $self->status->repeat
430 unless defined $mode; # toggle if no param
431 $mode = $mode ?
1 : 0; # force integer
432 $self->_send_command("repeat $mode\n");
437 # $mpd->random( [$random] );
439 # Set the random mode to $random (1 or 0). If $random is not specified then
440 # the random mode is toggled.
443 my ($self, $mode) = @_;
445 $mode = not $self->status->random
446 unless defined $mode; # toggle if no param
447 $mode = $mode ?
1 : 0; # force integer
448 $self->_send_command("random $mode\n");
453 # $mpd->fade( [$seconds] );
455 # Enable crossfading and set the duration of crossfade between songs. If
456 # $seconds is not specified or $seconds is 0, then crossfading is disabled.
459 my ($self, $value) = @_;
461 $self->_send_command("crossfade $value\n");
465 # -- MPD interaction: controlling playback
468 # $mpd->play( [$song] );
470 # Begin playing playlist at song number $song. If no argument supplied,
474 my ($self, $number) = @_;
475 $number = '' unless defined $number;
476 $self->_send_command("play $number\n");
480 # $mpd->playid( [$songid] );
482 # Begin playing playlist at song ID $songid. If no argument supplied,
486 my ($self, $number) = @_;
488 $self->_send_command("playid $number\n");
493 # $mpd->pause( [$sate] );
495 # Pause playback. If $state is 0 then the current track is unpaused, if
496 # $state is 1 then the current track is paused.
498 # Note that if $state is not given, pause state will be toggled.
501 my ($self, $state) = @_;
502 $state ||= ''; # default is to toggle
503 $self->_send_command("pause $state\n");
514 $self->_send_command("stop\n");
521 # Play next song in playlist.
525 $self->_send_command("next\n");
531 # Play previous song in playlist.
535 $self->_send_command("previous\n");
540 # $mpd->seek( $time, [$song] );
542 # Seek to $time seconds in song number $song. If $song number is not specified
543 # then the perl module will try and seek to $time in the current song.
546 my ($self, $time, $song) = @_;
547 $time ||= 0; $time = int $time;
548 $song = $self->status->song if not defined $song; # seek in current song
549 $self->_send_command( "seek $song $time\n" );
554 # $mpd->seekid( $time, [$songid] );
556 # Seek to $time seconds in song ID $songid. If $songid number is not specified
557 # then the perl module will try and seek to $time in the current song.
560 my ($self, $time, $song) = @_;
561 $time ||= 0; $time = int $time;
562 $song = $self->status->songid if not defined $song; # seek in current song
563 $self->_send_command( "seekid $song $time\n" );
577 Audio::MPD - class to talk to MPD (Music Player Daemon) servers
584 my $mpd = Audio::MPD->new;
592 C<Audio::MPD> gives a clear object-oriented interface for talking to and
593 controlling MPD (Music Player Daemon) servers. A connection to the MPD
594 server is established as soon as a new C<Audio::MPD> object is created.
596 Since mpd is still in 0.x versions, C<Audio::MPD> sticks to latest mpd
597 (0.14 as time of writing) protocol & behaviour, and does B<not> try to
598 maintain backward compatibility.
600 Note that the module will by default connect to mpd before sending any
601 command, and will disconnect after the command has been issued. This
602 scheme is far from optimal, but allows us not to care about timeout
603 disconnections. Because of that, the C<idle> command (new in mpd 0.14)
604 is B<not> (and will not) be supported in C<Audio::MPD>. This will be
605 implemented in L<POE::Component::Client::MPD>.
607 B</!\> Note that C<Audio::MPD> is using high-level, blocking sockets.
608 This means that if the mpd server is slow, or hangs for whatever reason,
609 or even crash abruptly, the program will be hung forever in this sub.
610 The L<POE::Component::Client::MPD> module is way safer - you're advised
611 to use it instead of C<Audio::MPD>. Or you can try to set C<conntype> to
612 C<$REUSE> (see C<Audio::MPD> constructor for more details), but you
613 would be then on your own to deal with disconnections.
624 This is the constructor for C<Audio::MPD>. One can specify the following
629 =item host => C<$hostname>
631 defaults to environment var C<MPD_HOST>, then to 'localhost'. Note that
632 C<MPD_HOST> can be of the form password@host.
634 =item port => C<$port>
636 defaults to environment var C<MPD_PORT>, then to 6600.
638 =item password => $password
640 defaults to environment var C<MPD_PASSWORD>, then to ''.
642 =item conntype => $type
644 change how the connection to mpd server is handled. It can be either
645 C<$REUSE> to reuse the same connection or C<$ONCE> to open a new
646 connection per command (default)
654 =head2 Controlling the server
660 Sends a ping command to the mpd server.
663 =item $mpd->version()
665 Return mpd's version number as advertised during connection. Note that
666 mpd returns B<protocol> version when connected. This protocol version
667 can differ from the real mpd version. eg, mpd version 0.13.2 is
668 "speaking" and thus advertising version 0.13.0.
674 Send a message to the MPD server telling it to shut down.
677 =item $mpd->password( [$password] )
679 Change password used to communicate with MPD server to C<$password>.
680 Empty string is assumed if C<$password> is not supplied.
683 =item $mpd->updatedb( [$path] )
685 Force mpd to recan its collection. If C<$path> (relative to MPD's music
686 directory) is supplied, MPD will only scan it - otherwise, MPD will
687 rescan its whole collection.
690 =item $mpd->urlhandlers()
692 Return an array of supported URL schemes.
698 =head2 Handling volume & output
702 =item $mpd->volume( [+][-]$volume )
704 Sets the audio output volume percentage to absolute C<$volume>. If
705 C<$volume> is prefixed by '+' or '-' then the volume is changed
706 relatively by that value.
709 =item $mpd->output_enable( $output )
711 Enable the specified audio output. C<$output> is the ID of the audio
715 =item $mpd->output_disable( $output )
717 Disable the specified audio output. C<$output> is the ID of the audio
723 =head2 Retrieving info from current state
729 Return an L<Audio::MPD::Common::Stats> object with the current statistics
730 of MPD. See the associated pod for more information.
735 Return an L<Audio::MPD::Common::Status> object with various information on
736 current MPD server settings. Check the embedded pod for more information on
737 the available accessors.
740 =item $mpd->current()
742 Return an L<Audio::MPD::Common::Item::Song> representing the song currently
746 =item $mpd->song( [$song] )
748 Return an L<Audio::MPD::Common::Item::Song> representing the song number
749 C<$song>. If C<$song> is not supplied, returns the current song.
752 =item $mpd->songid( [$songid] )
754 Return an L<Audio::MPD::Common::Item::Song> representing the song with id
755 C<$songid>. If C<$songid> is not supplied, returns the current song.
760 =head2 Altering MPD settings
764 =item $mpd->repeat( [$repeat] )
766 Set the repeat mode to C<$repeat> (1 or 0). If C<$repeat> is not
767 specified then the repeat mode is toggled.
770 =item $mpd->random( [$random] )
772 Set the random mode to C<$random> (1 or 0). If C<$random> is not
773 specified then the random mode is toggled.
776 =item $mpd->fade( [$seconds] )
778 Enable crossfading and set the duration of crossfade between songs. If
779 C<$seconds> is not specified or $seconds is 0, then crossfading is
785 =head2 Controlling playback
789 =item $mpd->play( [$song] )
791 Begin playing playlist at song number C<$song>. If no argument supplied,
795 =item $mpd->playid( [$songid] )
797 Begin playing playlist at song ID C<$songid>. If no argument supplied,
801 =item $mpd->pause( [$state] )
803 Pause playback. If C<$state> is 0 then the current track is unpaused,
804 if C<$state> is 1 then the current track is paused.
806 Note that if C<$state> is not given, pause state will be toggled.
816 Play next song in playlist.
821 Play previous song in playlist.
824 =item $mpd->seek( $time, [$song])
826 Seek to C<$time> seconds in song number C<$song>. If C<$song> number is
827 not specified then the perl module will try and seek to C<$time> in the
831 =item $mpd->seekid( $time, $songid )
833 Seek to C<$time> seconds in song ID C<$songid>. If C<$song> number is
834 not specified then the perl module will try and seek to C<$time> in the
840 =head2 Searching the collection
842 To search the collection, use the C<collection()> accessor, returning the
843 associated L<Audio::MPD::Collection> object. You will then be able to call:
845 $mpd->collection->random_song;
847 See L<Audio::MPD::Collection> documentation for more details on available
851 =head2 Handling the playlist
853 To update the playlist, use the C<playlist()> accessor, returning the
854 associated C<Audio::MPD::Playlist> object. You will then be able to call:
856 $mpd->playlist->clear;
858 See L<Audio::MPD::Playlist> documentation for more details on available
865 Please report any bugs or feature requests to
866 C<bug-audio-mpd@rt.cpan.org>, or through the web interface at
867 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Audio-MPD>. I will be
868 notified, and then you'll automatically be notified of progress on your
869 bug as I make changes.
875 You can find more information on the mpd project on its homepage at
876 L<http://www.musicpd.org>.wikia.com>.
878 C<Audio::MPD> development takes place on <audio-mpd@googlegroups.com>:
879 feel free to join us. (use L<http://groups.google.com/group/audio-mpd>
880 to sign in). Our git repository is located at
881 L<git://repo.or.cz/audio-mpd.git>, and can be browsed at
882 L<http://repo.or.cz/w/audio-mpd.git>.
885 You can also look for information on this module at:
889 =item * AnnoCPAN: Annotated CPAN documentation
891 L<http://annocpan.org/dist/Audio-MPD>
895 L<http://cpanratings.perl.org/d/Audio-MPD>
899 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Audio-MPD>
907 Jerome Quelin, C<< <jquelin@cpan.org> >>
909 Original code by Tue Abrahamsen C<< <tue.abrahamsen@gmail.com> >>,
910 documented by Nicholas J. Humfrey C<< <njh@aelius.com> >>.
913 =head1 COPYRIGHT & LICENSE
915 Copyright (c) 2005 Tue Abrahamsen, all rights reserved.
916 Copyright (c) 2006 Nicolas J. Humfrey, all rights reserved.
917 Copyright (c) 2007-2009 Jerome Quelin, all rights reserved.
919 This program is free software; you can redistribute it and/or modify
920 it under the same terms as Perl itself.