2 # This file is part of Audio::MPD
3 # Copyright (c) 2007 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.1';
33 Readonly
our $REUSE => 1;
34 Readonly
our $ONCE => 0;
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 # - hostname => $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);
197 sub _cooked_command_as_filename
{
198 my ($self, $command) = @_;
200 my @lines = $self->_send_command($command);
203 # parse lines in reverse order since "file:" or "directory:" lines
204 # come first. therefore, let's first store every other parameter,
205 # and the last line will trigger the object creation.
206 # of course, since we want to preserve the playlist order, this means
207 # that we're going to unshift the objects instead of push.
208 foreach my $line (@lines) {
209 my ($k,$v) = split /:\s/, $line, 2;
210 if ( $k eq 'file'){$param{$k} = $v;}
211 unshift @items, $param{'file'};
219 # my %hash = $mpd->_cooked_command_as_kv( $command );
221 # Lots of Audio::MPD methods are using _send_command() and then parse the
222 # output to get a list of key / value (with the colon ":" acting as separator).
223 # This method is meant to factorize this code, and will parse the raw output
224 # of _send_command() in a cooked hash.
226 sub _cooked_command_as_kv
{
227 my ($self, $command) = @_;
229 map { split(/:\s/, $_, 2) }
230 $self->_send_command($command);
235 # my @list = $mpd->_cooked_command_strip_first_field( $command );
237 # Lots of Audio::MPD methods are using _send_command() and then parse the
238 # output to remove the first field (with the colon ":" acting as separator).
239 # This method is meant to factorize this code, and will parse the raw output
240 # of _send_command() in a cooked list of strings.
242 sub _cooked_command_strip_first_field
{
243 my ($self, $command) = @_;
246 map { ( split(/:\s+/, $_, 2) )[1] }
247 $self->_send_command($command);
255 # -- MPD interaction: general commands
260 # Sends a ping command to the mpd server.
264 $self->_send_command( "ping\n" );
269 # my $version = $mpd->version;
271 # Return version of MPD server's connected.
273 # sub version {} # implemented as an accessor.
280 # Send a message to the MPD server telling it to shut down.
284 $self->_send_command("kill\n");
289 # $mpd->password( [$password] )
291 # Change password used to communicate with MPD server to $password.
292 # Empty string is assumed if $password is not supplied.
295 my ($self, $passwd) = @_;
297 $self->_password($passwd);
298 $self->ping; # ping sends a command, and thus the password is sent
303 # $mpd->updatedb( [$path] );
305 # Force mpd to rescan its collection. If $path (relative to MPD's music
306 # directory) is supplied, MPD will only scan it - otherwise, MPD will rescan
307 # its whole collection.
310 my ($self, $path) = @_;
312 $self->_send_command("update $path\n");
317 # my @handlers = $mpd->urlhandlers;
319 # Return an array of supported URL schemes.
323 return $self->_cooked_command_strip_first_field("urlhandlers\n");
327 # -- MPD interaction: handling volume & output
330 # $mpd->volume( [+][-]$volume );
332 # Sets the audio output volume percentage to absolute $volume.
333 # If $volume is prefixed by '+' or '-' then the volume is changed relatively
337 my ($self, $volume) = @_;
339 if ($volume =~ /^(-|\+)(\d+)/ ) {
340 my $current = $self->status->volume;
341 $volume = $1 eq '+' ?
$current + $2 : $current - $2;
343 $self->_send_command("setvol $volume\n");
348 # $mpd->output_enable( $output );
350 # Enable the specified audio output. $output is the ID of the audio output.
353 my ($self, $output) = @_;
354 $self->_send_command("enableoutput $output\n");
359 # $mpd->output_disable( $output );
361 # Disable the specified audio output. $output is the ID of the audio output.
364 my ($self, $output) = @_;
365 $self->_send_command("disableoutput $output\n");
370 # -- MPD interaction: retrieving info from current state
375 # Return an AMC::Stats object with the current statistics of MPD.
379 my %kv = $self->_cooked_command_as_kv( "stats\n" );
380 return Audio
::MPD
::Common
::Stats
->new(\
%kv);
385 # my $status = $mpd->status;
387 # Return an AMC::Status object with various information on current
388 # MPD server settings. Check the embedded pod for more information on the
389 # available accessors.
393 my %kv = $self->_cooked_command_as_kv( "status\n" );
394 my $status = Audio
::MPD
::Common
::Status
->new( \
%kv );
400 # my $song = $mpd->current;
402 # Return an AMC::Item::Song representing the song currently playing.
406 my ($item) = $self->_cooked_command_as_items("currentsong\n");
412 # my $song = $mpd->song( [$song] )
414 # Return an AMC::Item::Song representing the song number $song.
415 # If $song is not supplied, returns the current song.
418 my ($self, $song) = @_;
419 return $self->current unless defined $song;
420 my ($item) = $self->_cooked_command_as_items("playlistinfo $song\n");
426 # my $song = $mpd->songid( [$songid] )
428 # Return an AMC::Item::Song representing the song with id $songid.
429 # If $songid is not supplied, returns the current song.
432 my ($self, $songid) = @_;
433 return $self->current unless defined $songid;
434 my ($item) = $self->_cooked_command_as_items("playlistid $songid\n");
439 # -- MPD interaction: altering settings
442 # $mpd->repeat( [$repeat] );
444 # Set the repeat mode to $repeat (1 or 0). If $repeat is not specified then
445 # the repeat mode is toggled.
448 my ($self, $mode) = @_;
450 $mode = not $self->status->repeat
451 unless defined $mode; # toggle if no param
452 $mode = $mode ?
1 : 0; # force integer
453 $self->_send_command("repeat $mode\n");
458 # $mpd->random( [$random] );
460 # Set the random mode to $random (1 or 0). If $random is not specified then
461 # the random mode is toggled.
464 my ($self, $mode) = @_;
466 $mode = not $self->status->random
467 unless defined $mode; # toggle if no param
468 $mode = $mode ?
1 : 0; # force integer
469 $self->_send_command("random $mode\n");
474 # $mpd->fade( [$seconds] );
476 # Enable crossfading and set the duration of crossfade between songs. If
477 # $seconds is not specified or $seconds is 0, then crossfading is disabled.
480 my ($self, $value) = @_;
482 $self->_send_command("crossfade $value\n");
486 # -- MPD interaction: controlling playback
489 # $mpd->play( [$song] );
491 # Begin playing playlist at song number $song. If no argument supplied,
495 my ($self, $number) = @_;
496 $number = '' unless defined $number;
497 $self->_send_command("play $number\n");
501 # $mpd->playid( [$songid] );
503 # Begin playing playlist at song ID $songid. If no argument supplied,
507 my ($self, $number) = @_;
509 $self->_send_command("playid $number\n");
514 # $mpd->pause( [$sate] );
516 # Pause playback. If $state is 0 then the current track is unpaused, if
517 # $state is 1 then the current track is paused.
519 # Note that if $state is not given, pause state will be toggled.
522 my ($self, $state) = @_;
523 $state ||= ''; # default is to toggle
524 $self->_send_command("pause $state\n");
535 $self->_send_command("stop\n");
542 # Play next song in playlist.
546 $self->_send_command("next\n");
552 # Play previous song in playlist.
556 $self->_send_command("previous\n");
561 # $mpd->seek( $time, [$song] );
563 # Seek to $time seconds in song number $song. If $song number is not specified
564 # then the perl module will try and seek to $time in the current song.
567 my ($self, $time, $song) = @_;
568 $time ||= 0; $time = int $time;
569 $song = $self->status->song if not defined $song; # seek in current song
570 $self->_send_command( "seek $song $time\n" );
575 # $mpd->seekid( $time, [$songid] );
577 # Seek to $time seconds in song ID $songid. If $songid number is not specified
578 # then the perl module will try and seek to $time in the current song.
581 my ($self, $time, $song) = @_;
582 $time ||= 0; $time = int $time;
583 $song = $self->status->songid if not defined $song; # seek in current song
584 $self->_send_command( "seekid $song $time\n" );
598 Audio::MPD - class to talk to MPD (Music Player Daemon) servers
605 my $mpd = Audio::MPD->new();
613 Audio::MPD gives a clear object-oriented interface for talking to and
614 controlling MPD (Music Player Daemon) servers. A connection to the MPD
615 server is established as soon as a new Audio::MPD object is created.
617 Note that the module will by default connect to mpd before sending any
618 command, and will disconnect after the command has been issued. This scheme
619 is far from optimal, but allows us not to care about timeout disconnections.
621 B</!\> Note that Audio::MPD is using high-level, blocking sockets. This
622 means that if the mpd server is slow, or hangs for whatever reason, or
623 even crash abruptly, the program will be hung forever in this sub. The
624 POE::Component::Client::MPD module is way safer - you're advised to use
625 it instead of Audio::MPD. Or you can try to set C<conntype> to C<$REUSE>
626 (see Audio::MPD constructor for more details), but you would be then on
627 your own to deal with disconnections.
638 This is the constructor for Audio::MPD. One can specify the following
643 =item hostname => C<$hostname>
645 defaults to environment var MPD_HOST, then to 'localhost'. Note that
646 MPD_HOST can be of the form password@host.
648 =item port => C<$port>
650 defaults to environment var MPD_PORT, then to 6600.
652 =item password => $password
654 defaults to environment var MPD_PASSWORD, then to ''.
656 =item conntype => $type
658 change how the connection to mpd server is handled. It can be either
659 C<$REUSE> to reuse the same connection or C<$ONCE> to open a new
660 connection per command (default)
668 =head2 Controlling the server
674 Sends a ping command to the mpd server.
677 =item $mpd->version()
679 Return the version number for the server we are connected to.
684 Send a message to the MPD server telling it to shut down.
687 =item $mpd->password( [$password] )
689 Change password used to communicate with MPD server to $password.
690 Empty string is assumed if $password is not supplied.
693 =item $mpd->updatedb( [$path] )
695 Force mpd to recan its collection. If $path (relative to MPD's music directory)
696 is supplied, MPD will only scan it - otherwise, MPD will rescan its whole
700 =item $mpd->urlhandlers()
702 Return an array of supported URL schemes.
708 =head2 Handling volume & output
712 =item $mpd->volume( [+][-]$volume )
714 Sets the audio output volume percentage to absolute $volume.
715 If $volume is prefixed by '+' or '-' then the volume is changed relatively
719 =item $mpd->output_enable( $output )
721 Enable the specified audio output. $output is the ID of the audio output.
724 =item $mpd->output_disable( $output )
726 Disable the specified audio output. $output is the ID of the audio output.
731 =head2 Retrieving info from current state
737 Return an C<Audio::MPD::Common::Stats> object with the current statistics
738 of MPD. See the associated pod for more information.
743 Return an C<Audio::MPD::Common::Status> object with various information on
744 current MPD server settings. Check the embedded pod for more information on
745 the available accessors.
748 =item $mpd->current()
750 Return an C<Audio::MPD::Common::Item::Song> representing the song currently
754 =item $mpd->song( [$song] )
756 Return an C<Audio::MPD::Common::Item::Song> representing the song number
757 C<$song>. If C<$song> is not supplied, returns the current song.
760 =item $mpd->songid( [$songid] )
762 Return an C<Audio::MPD::Common::Item::Song> representing the song with id
763 C<$songid>. If C<$songid> is not supplied, returns the current song.
768 =head2 Altering MPD settings
772 =item $mpd->repeat( [$repeat] )
774 Set the repeat mode to $repeat (1 or 0). If $repeat is not specified then
775 the repeat mode is toggled.
778 =item $mpd->random( [$random] )
780 Set the random mode to $random (1 or 0). If $random is not specified then
781 the random mode is toggled.
784 =item $mpd->fade( [$seconds] )
786 Enable crossfading and set the duration of crossfade between songs.
787 If $seconds is not specified or $seconds is 0, then crossfading is disabled.
792 =head2 Controlling playback
796 =item $mpd->play( [$song] )
798 Begin playing playlist at song number $song. If no argument supplied,
802 =item $mpd->playid( [$songid] )
804 Begin playing playlist at song ID $songid. If no argument supplied,
808 =item $mpd->pause( [$state] )
810 Pause playback. If C<$state> is 0 then the current track is unpaused,
811 if $state is 1 then the current track is paused.
813 Note that if C<$state> is not given, pause state will be toggled.
823 Play next song in playlist.
828 Play previous song in playlist.
831 =item $mpd->seek( $time, [$song])
833 Seek to $time seconds in song number $song. If $song number is not specified
834 then the perl module will try and seek to $time in the current song.
837 =item $mpd->seekid( $time, $songid )
839 Seek to $time seconds in song ID $songid. If $song number is not specified
840 then the perl module will try and seek to $time in the current song.
845 =head2 Searching the collection
847 To search the collection, use the C<collection()> accessor, returning the
848 associated C<Audio::MPD::Collection> object. You will then be able to call:
850 $mpd->collection->random_song();
852 See C<Audio::MPD::Collection> documentation for more details on available
856 =head2 Handling the playlist
858 To update the playlist, use the C<playlist()> accessor, returning the
859 associated C<Audio::MPD::Playlist> object. You will then be able to call:
861 $mpd->playlist->clear;
863 See C<Audio::MPD::Playlist> documentation for more details on available
869 You can find more information on the mpd project on its homepage at
870 L<http://www.musicpd.org>, or its wiki L<http://mpd.wikia.com>.
872 Regarding this Perl module, you can report bugs on CPAN via
873 L<http://rt.cpan.org/Public/Bug/Report.html?Queue=Audio-MPD>.
875 Audio::MPD development takes place on <audio-mpd@googlegroups.com>: feel free
876 to join us. (use L<http://groups.google.com/group/audio-mpd> to sign in). Our
877 subversion repository is located at L<https://svn.musicpd.org>.
882 Jerome Quelin, C<< <jquelin at cpan.org> >>
884 Original code by Tue Abrahamsen C<< <tue.abrahamsen at gmail.com> >>,
885 documented by Nicholas J. Humfrey C<< <njh at aelius.com> >>.
888 =head1 COPYRIGHT & LICENSE
890 Copyright (c) 2005 Tue Abrahamsen, all rights reserved.
891 Copyright (c) 2006 Nicolas J. Humfrey, all rights reserved.
892 Copyright (c) 2007 Jerome Quelin, all rights reserved.
894 This program is free software; you can redistribute it and/or modify
895 it under the same terms as Perl itself.