Debian Codegraph @

mpfade

raw
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4 use Audio::MPD q{0.19.0};
5
6 =head1 NAME
7
8 mpfade - fade mpd volume in or out
9
10 =head1 SYNOPSIS
11
12 mpfade [minutes] [max|min] [host]
13
14 =head1 DESCRIPTION
15
16 B<mpfade> behaves differently depending on whether mpd is playing or not.
17
18 If mpd is not playing (or is paused), it starts it playing at a low volume,
19 and gradually cranks the volume up to the specified B<max> value (default
20 50) over the specified number of minutes (default 10).
21
22 If mpd is already playing, it works in reverse, reducing the volume over
23 time until it's a the specified B<min> (defaults to a tenth of what it was
24 at the start). Then it stops playing.
25
26 B<mpfade> tries to interact well with manual volume changes you make. If
27 the volume is fading up, and you change the volume manually, it stops. This
28 is intended to be useful when used as an alarm clock. If the volume is
29 fading down, changes you make to the volume will be noticed, and the fade
30 down will continue from that point.
31
32 The B<minutes> value can be a floating point value. If the hostname is
33 omitted, the MPD_HOST environment variable will be used.
34
35 =head1 AUTHOR
36
37 Copyright 2007 Joey Hess <[email protected]>
38
39 Licensed under the GNU GPL version 2 or higher.
40
41 http://kitenet.net/~joey/code/mpdtoys
42
43 =cut
44
45 my $seconds=60 * 10;
46 if (@ARGV && $ARGV[0] =~ /^[0-9.]+$/) {
47 $seconds=60 * shift;
48 }
49 my $endpoint;
50 if (@ARGV && $ARGV[0] =~ /^[0-9.]+$/) {
51 $endpoint=shift;
52 }
53
54 if (@ARGV) {
55 $ENV{MPD_HOST}=shift;
56 }
57
58 my $mpd=Audio::MPD->new(conntype => "reuse");
59 my $vol=$mpd->status->volume;
60 if ($mpd->status->state eq 'play') {
61 if (defined $endpoint) {
62 if ($endpoint >= $vol) {
63 die "error: min ($endpoint) is not less than current volume ($vol)\n";
64 }
65 }
66 else {
67 $endpoint=int($vol / 10);
68 }
69 print "fading down from $vol to $endpoint over $seconds seconds\n";
70 fade($endpoint, $seconds);
71 $mpd->stop;
72 }
73 else {
74 if (! defined $endpoint) {
75 $endpoint=50;
76 }
77 $mpd->volume($vol=0);
78 print "fading up from $vol to $endpoint over $seconds seconds\n";
79 $mpd->play;
80 fade($endpoint, $seconds);
81 }
82
83 sub fade {
84 my $endpoint=shift;
85 my $seconds=shift;
86
87 if ($seconds < 1) {
88 $mpd->volume($endpoint);
89 return;
90 }
91
92 my $span=$endpoint - $vol;
93 my $oldvol=$vol;
94 my $curvol;
95
96 # TODO calculate how long to optimally sleep
97
98 while (sleep 1) {
99 $curvol=$mpd->status->volume;
100 if ($curvol != $oldvol) {
101 if ($span > 0) {
102 print "manual volume change, aborting fade up\n";
103 return;
104 }
105 else {
106 print "manual volume change\n";
107 $vol=$curvol;
108 }
109 }
110
111 $vol=$vol + ($span / $seconds);
112 last if abs($vol - $endpoint) <= 1;
113 if (abs(int($vol - $oldvol)) > 1) {
114 $mpd->volume(int($vol));
115 $oldvol=int($vol);
116 }
117 }
118 }