-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaudio-player3
executable file
·896 lines (769 loc) · 24.3 KB
/
audio-player3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
#!/usr/bin/env perl
=head1 NAME
audio-player3
=head1 DESCRIPTION
This program is the evolution of audioplayer2, and is a lightweight,
simple audio server.
This app has logic to fetch cover art from the L<last.fm> API. In
order to do this, the artist, track and album names are divined (with
regular expressions). Change this in the source below for your
filenames.
Write-up: https://ology.github.io/2021/06/04/mojolicious-music-player/
=head1 SYNOPSIS
This app depends on a directory (or symbolic link) called C<Audio> in
the C<public> directory.
On unix-like systems, symlink your audio source:
audio-player/public $ ln -s /media/you/external_drive/Music/ Audio
Or on windows, as the Administrator:
mklink /D C:\Users\you\wherever\audio-player\public\Audio "X:\My Music"
Then:
audio-player $ morbo audio-player3
And browse to:
http://127.0.0.1:3000/refresh
=cut
use Mojolicious::Lite -signatures;
use Data::Dumper::Compact qw(ddc);
use Encoding::FixLatin qw(fix_latin);
use File::Find::Rule ();
use List::SomeUtils qw(first_index);
use Mojo::Util qw(url_unescape);
use Number::Format ();
use Storable qw(retrieve store);
use Try::Tiny;
use lib map { "$ENV{HOME}/sandbox/$_/lib" } qw(WebService-LastFM-TrackInfo);
use WebService::LastFM::TrackInfo;
use YAML::XS qw(LoadFile);
use constant RATES => (0 .. 5); #qw(None Bad Poor Fair Good Best);
use constant EXTS => qr/\.(flac|m4a|mp3|ogg|wav)$/i; # Tracks of interest
use constant PATH => 'public/Audio/'; # Where the audio files live
use constant TRACKS => app->moniker . '.dat'; # The tracks file
# ./config.yml file:
# api_key: 'abcdef123456'
my $config = LoadFile 'config.yml';
my $API_KEY = $config->{api_key}; # for last.fm
=head1 ROUTES
=head2 GET /
The main endpoint and player page.
Name: C<index>
=cut
get '/' => sub ($c) {
my $autoadvance = $c->param('autoadvance') || 0; # Automatically move to the next track
my $autoplay = $c->param('autoplay') || 0; # Start playing the current track
my $current = $c->param('current') || 0; # The last and next played track
my $noinc = $c->param('noinc') || 0; # Do not increment to the next track
my $shuffle = $c->param('shuffle') || 0; # Select a random track to play next
my $query = $c->param('query') || ''; # The url encoded search query
my $showrate = $c->param('showrate') || ''; # Filter by the requested rate
my $darkmode = $c->param('darkmode') || 0; # Use dark mode
my ($op, $rate) = split / /, $showrate;
my $audio = {}; # Bucket for all tracks
my $match = []; # Bucket for all query matches
# Load the track list or flash an error
if (-e TRACKS) {
$audio = retrieve(TRACKS);
}
else {
$c->flash(message => 'Cannot read track list file. Please <a href="/refresh">refresh</a>');
}
if (keys %$audio) {
if ($query) {
# Convert encoded things like %26 back into &
$query = url_unescape($query);
# Brute force through every track, looking for matches
for my $key (sort { $a <=> $b } keys %$audio) {
next if $showrate && !_in_rate_range($op, $rate, $audio->{$key}{rating});
push @$match, $key if lc($audio->{$key}{track}) =~ /$query/i;
}
# Accumulate the matches
my %tracks;
for my $n (@$match) {
$tracks{ $audio->{$n}{track} } = $n;
}
$match = [ map { $tracks{$_} } sort { $a cmp $b } keys %tracks ];
$current = _get_current($match, $current, $shuffle, $noinc);
}
# Don't compute track rates if not incrementing
elsif ($showrate && !$noinc) {
my $filtered = [];
# Gather the rated tracks
for my $trk (sort { $a <=> $b } keys %$audio) {
next if !_in_rate_range($op, $rate, $audio->{$trk}{rating});
push @$filtered, $trk;
}
$current = _get_current($filtered, $current, $shuffle, $noinc);
}
else {
# If shuffling, get a random audio track index, otherwise increment... or don't.
$current = $shuffle && !$noinc
? int(rand keys %$audio)
: $noinc
? $current
: $current + 1;
}
}
# Handle the undef case that makes bad things happen
$current = -1 unless defined $current;
# get the track and rating
my $track = '';
my $rating = 0;
if (keys %$audio) {
$track = $current >= 0 ? $audio->{$current}{track} : '';
$rating = $current >= 0 ? $audio->{$current}{rating} : 0;
}
# app->log->debug("Current: $current, Track: $track");
# Add a number separator comma
my $nf = Number::Format->new;
my $total = $nf->format_number(scalar keys %$audio);
my $matches = $nf->format_number(scalar @$match);
# Parse the track name and find an image
my $track_info;
my $track_image;
if ($track) {
my @parts = split /\//, $track;
my $name = $parts[-1]; # track name
my $album = $parts[-2]; # album name
my $artist = $parts[-3]; # but not always
# Handle cases like:
# 01 Tom Sawyer-1647382734.mp3
# 1-02 Mingulay Boat Song-1647389909.mp3
# 05 Let Me Tell You About My Boat.m4a
# New Day-6SumbNBSEo8.m4a
# Revolution 1 (Remastered 2009)-OmsXsIv2Ppw.m4a
# A Reminiscent Drive - Ambrosia-rP89haLVP4k.m4a
# Van Halen - Hot For Teacher (Official Music Video)-6M4_Ommfvv0.m4a
$name =~ s/^(?:\d+-)?\d+\s+(.*?)/$1/;
$name =~ s/(.*?)-\d+\.mp3$/$1/;
$name =~ s/(.*?)\.mp3$/$1/;
$name =~ s/(.*?)-[\w-]+\.m4a$/$1/;
$name =~ s/(.*?)\.m4a$/$1/;
$name =~ s/(.*?) \((?:Official )?Audio\)/$1/;
$name =~ s/(.*?) \(Remastered(?: \d+)?\)/$1/;
$name =~ s/(.*?) \(\d+ Remaster\)/$1/;
$name =~ s/(.*?) \(Official\s*(?:Lyric|Music)?\s*Video\)/$1/;
$name =~ s/$artist\s*-\s*(.*?)$/$1/;
# Special cases
if ($track =~ /Hôtel Costes/) {
$name =~ s/Hotel Costes \d+ - (.*)$/$1/;
my ($who, $what) = split /\s*-\s*/, $name, 2;
($artist, $name) = ($who, $what)
if $who && $what;
}
# Find an image
my $w = WebService::LastFM::TrackInfo->new(api_key => $API_KEY);
try {
$track_info = $w->fetch(
artist => $artist,
track => $name,
);
};
$track_image = _get_image($track_info->{track}{album});
unless ($track_image) {
$w = WebService::LastFM::TrackInfo->new(
api_key => $API_KEY,
method => 'album',
);
try {
$track_info = $w->fetch(
artist => $artist,
album => $album,
);
};
$track_image = _get_image($track_info->{album});
}
$track_info->{computed_title} = "|$artist| |$album| |$name|";
}
$c->render(
template => 'index',
audio => $audio,
total => $total,
track => $track,
track_info => ddc($track_info, {max_width => 128}),
track_image => $track_image,
rating => $rating,
autoplay => $autoplay,
autoadvance => $autoadvance,
current => $current,
shuffle => $shuffle,
query => $query,
match => $match,
matches => $matches,
showrate => $showrate,
ratings => [RATES],
darkmode => $darkmode,
);
} => 'index';
sub _get_image ($data) {
return undef unless $data->{image} && @{ $data->{image} };
my $image;
for my $item (@{ $data->{image} }) {
if ($item->{size} eq 'extralarge' && $item->{'#text'}) {
$image = $item->{'#text'};
last;
}
}
return $image;
}
sub _get_current ($match, $current, $shuffle, $noinc) {
# If shuffling, get a random member of the matches,
# otherwise increment, unless we are told not to
if ($shuffle && !$noinc) {
$current = $match->[int rand @$match];
}
else {
# Find the index of the current item in the search results
my $idx = first_index { $_ == $current } @$match;
$idx = 0 if $idx == -1;
# To increment, or not to increment...
if ($noinc) {
$current = $match->[$idx];
}
else {
$current = $match->[$idx + 1];
}
}
return $current;
}
sub _in_rate_range ($op, $rate, $track_rating) {
my $in_range = 0;
if ($op eq '<') {
$in_range++ if $track_rating < $rate;
}
elsif ($op eq '=') {
$in_range++ if $track_rating == $rate;
}
elsif ($op eq '>') {
$in_range++ if $track_rating > $rate;
}
return $in_range;
}
=head2 GET /refresh
Track file initialize and refresh endpoint that redirects back to the
C<index>.
Name: C<refresh>
=cut
get '/refresh' => sub ($c) {
# If a previous track file exists, use its ratings
my $old = {};
if (-e TRACKS) {
$old = retrieve(TRACKS);
}
# Assume there are no duplicate tracks
my %by_name;
for my $i (keys %$old) {
$by_name{ $old->{$i}{track} } = $old->{$i}{rating};
}
# Process the filenames
my $audio = {};
my @files = File::Find::Rule->file()->name(EXTS)->in(PATH);
my $n = 0;
for my $file (@files) {
# Remove "public" from the name
$file =~ s/^public//;
# Make sure the name is properly displayable
$file = fix_latin($file);
# Determine the track rating
my $rate = 0;
$rate = $by_name{$file}
if exists $by_name{$file};
# Add an entry to the audio list
$audio->{$n} = { track => $file, rating => $rate };
$n++;
}
# Save the files to disk
store $audio, TRACKS;
$c->flash(message => 'Saved track list file');
$c->redirect_to($c->url_for('index'));
} => 'refresh';
=head2 POST /rating
Track rating endpoint that renders a success or failure text message.
Name: C<rating>
=cut
post '/rating' => sub ($c) {
my $track = $c->param('current');
my $rate = $c->param('rating');
my $audio = retrieve(TRACKS);
my $message = 'Failed to rate track!';
if (exists $audio->{$track}) {
$audio->{$track}{rating} = $rate;
store $audio, TRACKS;
$message = "Rated track $track at $rate";
}
$c->render(text => $message);
} => 'rating';
=head2 GET /stats
Track stats endpoint that renders a page with rating counts.
Name: C<stats>
=cut
get '/stats' => sub ($c) {
my $audio = retrieve(TRACKS);
my ($total, $rated, $rate, $by_genre) = (0, 0, {}, {});
for my $key (keys %$audio) {
my $r = $audio->{$key}{rating};
$rated++ if $r;
$rate->{$r}++;
$total++;
(my $genre = $audio->{$key}{track}) =~ s|^/Audio/(.+?)/.+$|$1|;
$by_genre->{$genre}++ if $audio->{$key}{rating};
}
$c->render(
template => 'stats',
total => $total,
rated => $rated,
rate => $rate,
by_genre => $by_genre,
);
} => 'stats';
app->start;
=head1 AUTHOR
Gene Boggs <[email protected]>
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2022 by Gene Boggs.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)
=cut
__DATA__
@@ index.html.ep
% layout 'default';
% title 'Music!';
% # Flash error/message
% if (flash('error')) {
%= tag h4 => (style => 'color:red') => sub { flash('error') }
% }
% if (flash('message')) {
%= tag h4 => (style => 'color:green') => sub { flash('message') }
% }
% if ($track_image) {
<div>
<img src="<%= $track_image %>"/>
<p></p>
</div>
% }
% # Checkboxes
<div>
<label for="autoadvance"><b>Advance:</b></label>
<input type="checkbox" id="autoadvance" name="autoadvance" title="Automatically advance to the next track (a)" <%= $autoadvance ? 'checked' : '' %> />
<label for="autoplay"><b>Play:</b></label>
<input type="checkbox" id="autoplay" name="autoplay" title="Automatically start playing the current track (p)" <%= $autoplay ? 'checked' : '' %> />
<label for="shuffle"><b>Shuffle:</b></label>
<input type="checkbox" id="shuffle" name="shuffle" title="Select a random track (e)" <%= $shuffle ? 'checked' : '' %> />
<label for="darkmode"><b>Dark:</b></label>
<input type="checkbox" id="darkmode" name="darkmode" title="Toggle dark/light mode (d)" <%= $darkmode ? 'checked' : '' %> />
</div>
% # Current track name
<p id="track"><b>Track:</b> <%= $track %></p>
% # Audio widget
<p>
<div>
<audio controls id="myAudio" <%= $autoplay ? "autoplay='autoplay'" : '' %> preload="auto" crossorigin="anonymous" src="<%== $track %>" title="Audio controls (c) - Pause/play (y)">
Your browser does not support the <code>audio</code> element.
</audio>
<div id="warning"><b>Could not load audio!</b></div>
</div>
</p>
% # Rate track
<div>
<b><a href="<%= url_for('stats') %>" id="statslink" title="Inspect rating stats">Rating</a>:</b>
% for my $rate (0 .. $#$ratings) {
<input type="radio" name="rating" value="<%= $rate %>" <%= $rate == $rating ? 'checked' : '' %> title="<%= $ratings->[$rate] %>" />
% }
<select id="showrate" name="showrate" class="btn btn-mini" title="Filter by rating (r)">
<option value="">Any</option>
% for my $show (
% '< 1', '= 1', '> 1',
% '< 2', '= 2', '> 2',
% '< 3', '= 3', '> 3',
% '< 4', '= 4', '> 4',
% '< 5'
% ) {
<option value="<%= $show %>" <%= $showrate eq $show ? 'selected' : '' %>><%= $show %></option>
% }
</select>
</div>
% # Playlist history select
<p></p>
<p>
<select id="playlist" name="playlist" class="form-control input-lg" title="Playback history (h)">
<option value="" disabled selected>History</option>
</select>
<i class="fa fa-chevron-down"></i>
</p>
% # Search query
<div class="input-group">
<input type="search" id="query" name="query" class="form-control" placeholder="Search" value="<%= $query %>" title="Track search query (s)" />
<div class="input-group-append">
<button type="button" id="clearsearch" class="btn btn-outline-secondary" title="Clear the search query (x)">
<i class="fa fa-times"></i>
</button>
<button type="button" id="submitsearch" class="btn btn-outline-secondary rounded-right" title="Submit the search query">
<i class="fa fa-chevron-right"></i>
</button>
</div>
</div>
% # Track buttons
<p></p>
<p>
<button id="firsttrack" class="btn btn-outline-dark" title="Move to the first track (f)"><i class="fa fa-fast-backward" aria-hidden="true"></i> First</button>
<button id="nexttrack" class="btn btn-outline-dark" title="Advance to the next track (n)">Next <i class="fa fa-step-forward" aria-hidden="true"></i></button>
<span id="total" class="text-secondary"><%= $total %> tracks</span>
</p>
% # Search query matches
% if (@$match) {
<p></p>
<p><b>Matches:</b> <%= $matches %></p>
<ol>
% for my $n (@$match) {
<li>
% if ($track eq $audio->{$n}{track}) {
<b><a href="#" class="trackmatch" data-current="<%= $n %>"><%= $audio->{$n}{track} %></a></b>
% } else {
<a href="#" class="trackmatch" data-current="<%= $n %>"><%= $audio->{$n}{track} %></a>
% }
</li>
% }
</ol>
% } else {
% if ($query) {
<p></p>
<p id="no_matches">No matches</p>
% }
% }
% # Track info
% if ($track_info) {
<p></p>
<pre><%= $track_info %></pre>
% }
<script>
$(document).ready( function () {
% # Replace classes when in dark mode
if (<%= $darkmode %> || (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
$('#clearsearch').attr('class', 'btn btn-outline-white rounded-right');
$('#submitsearch').attr('class', 'btn btn-outline-light');
$('#firsttrack').attr('class', 'btn btn-outline-light');
$('#nexttrack').attr('class', 'btn btn-outline-light');
$('[class="text-secondary"]').attr('class', 'text-medium');
$('body').toggleClass('dark');
$('input[name=darkmode]').attr('checked', true);
}
% # Rate track function
function rating (r) {
$.ajax({
url: "<%= url_for('rating') %>" + '?current=' + <%= $current %> + '&rating=' + r,
method: 'POST',
success: function(data, textStatus, jqXHR) {
console.log('Rating: ' + r);
},
error: function(jqXHR, textStatus, error) {
console.log('Rating: ' + error);
}
});
}
% # Advance track function
function advance (force = 0, current = -1, noinc = 0, useq = 1) {
var showrate = $('select[name=showrate] option').filter(':selected').val();
var query = '';
if (useq == 1) {
query = $('input[name=query]').val();
}
if (current == -1) {
current = <%= $current || 0 %>;
}
var shuffle = 0;
if ($('#shuffle').is(':checked')) {
shuffle = 1;
}
var autoplay = 0;
if ($('#autoplay').is(':checked')) {
autoplay = 1;
}
autoadvance = 0;
if ($('#autoadvance').is(':checked')) {
autoadvance = 1;
}
darkmode = 0;
if ($('#darkmode').is(':checked')) {
darkmode = 1;
}
if (force == 1 || autoadvance == 1) {
var link = "<%= url_for('index') %>?current=" + current
+ '&noinc=' + noinc
+ '&query=' + encodeURIComponent(query)
+ '&shuffle=' + shuffle
+ '&autoplay=' + autoplay
+ '&autoadvance=' + autoadvance
+ '&showrate=' + showrate
+ '&darkmode=' + darkmode;
window.location = link;
}
}
% # Keep track of the volume
var vol = localStorage.getItem('playback_volume');
if (vol === null) {
vol = 1;
localStorage.setItem('playback_volume', vol);
}
% # Keep track of the played audio history
//var plh = []; // Reset history
//localStorage.setItem('playlist_history', JSON.stringify(plh)); // Reset history & comment the next 5 lines:
var plh = JSON.parse(localStorage.getItem('playlist_history'));
if (plh === null) {
plh = [];
localStorage.setItem('playlist_history', JSON.stringify(plh));
}
var max = 10;
var j = 0;
for (var i = plh.length; i >= 0; i--) {
for (var key in plh[i]) {
if (plh[i].hasOwnProperty(key)) {
$('#playlist').append($('<option>', {
text: key,
value: plh[i][key]
}));
}
}
if (j >= max) {
break;
}
j++;
}
% # Miscellaneous jQuery on events
$('#playlist').on('change', function () {
var current = $(this).children('option:selected').val();
advance(1, current, 1, 0);
});
// Submit a search query
$('#query').on('keypress', function (e) {
if (e.which == 13) {
// Submit = ENTER
advance();
}
});
$(document).on('keypress', function (e) {
var x = $('#query').is(':focus');
if (!x) {
var rate = -1; // For rating below
if (e.which == 99) {
// Audio controls = c
$('#myAudio').focus();
}
else if (e.which == 121) {
// Pause-Play = y
var audio = document.getElementById('myAudio');
if (audio.paused) {
audio.play();
}
else {
audio.pause();
}
}
else if (e.which == 102) {
// First track = f
advance(1, 0, 1, 0);
}
else if (e.which == 110) {
// Next track = n
advance(1);
}
else if (e.which == 114) {
// Rate filter focus = r
$('#showrate').focus();
}
else if (e.which == 104) {
// History playlist focus = h
$('#playlist').focus();
}
else if (e.which == 120) {
// Clear search query = x
$('#clearsearch').click();
}
else if (e.which == 115) {
// Search query focus = s
$('#query').focus();
}
else if (e.which >= 48 && e.which <= 53) {
// Track rating = 0-5
rate = e.which - 48;
}
else if (e.which == 97) {
// Advance = a
if ($('#autoadvance').is(':checked')) {
$('input[name=autoadvance]').attr('checked', false);
}
else {
$('input[name=autoadvance]').attr('checked', true);
}
}
else if (e.which == 112) {
// Play = p
if ($('#autoplay').is(':checked')) {
$('input[name=autoplay]').attr('checked', false);
}
else {
$('input[name=autoplay]').attr('checked', true);
}
}
else if (e.which == 101) {
// Shuffle = e
if ($('#shuffle').is(':checked')) {
$('input[name=shuffle]').attr('checked', false);
}
else {
$('input[name=shuffle]').attr('checked', true);
}
}
else if (e.which == 100) {
// Dark mode = d
if ($('#darkmode').is(':checked')) {
$('input[name=darkmode]').attr('checked', false);
}
else {
$('input[name=darkmode]').attr('checked', true);
}
}
if (rate >= 0) {
$('input[name=rating]:checked').attr('checked', false);
$('input[name=rating][value=' + rate + ']').attr('checked', 'checked');
rating(rate);
}
}
});
$('input[type=radio]').on('click', function() {
var r = $('input[name=rating]:checked').val();
rating(r);
});
$('#clearsearch').on('click', function() {
$('input[name=query]').val('');
});
$('#firsttrack').on('click', function() {
advance(1, 0, 1, 0);
});
$('#nexttrack').on('click', function() {
advance(1);
});
$('#submitsearch').on('click', function() {
advance(1);
});
$('.trackmatch').on('click', function() {
current = $(this).attr('data-current');
advance(1, current, 1);
});
% # Hide the playback warning
$('#warning').hide();
% # Disable the rating radios
$('input[name=rating]').attr('disabled', true);
% # Configure the audio element
$('#myAudio').focus();
$('#myAudio').attr('src', "<%== $track %>");
$('#myAudio').on('error', function() {
if ("<%= $track %>") {
console.log('Playback error!');
rating(-1);
$('#warning').show();
advance();
}
});
$('#myAudio').on('loadedmetadata', function() {
console.log('Loaded metadata');
document.getElementById('myAudio').volume = vol;
});
$('#myAudio').on('volumechange', function() {
var v = document.getElementById('myAudio').volume;
localStorage.setItem('playback_volume', v);
console.log('Volume: ' + v);
});
$('#myAudio').on('playing', function() {
console.log('Playing: ' + <%= $current %>);
$('input[name=rating]').attr('disabled', false);
});
$('#myAudio').on('ended', function() {
console.log('...Ended');
if (plh.length >= max) {
plh.shift();
}
plh.push({ "<%== $track %>": "<%= $current %>" });
localStorage.setItem('playlist_history', JSON.stringify(plh));
advance();
});
});
</script>
@@ stats.html.ep
% layout 'default';
% title 'Music stats';
<p><b>Total:</b> <%= $total %></p>
<p><b>Rated:</b> <%= $rated %> (<%= sprintf '%.2f', $rated / $total * 100 %>%)</p>
<hr>
% for my $i (sort { $a <=> $b } keys %$rate) {
<p><b><%= $i %> rating:</b> <%= $rate->{$i} %> (<%= sprintf '%.2f', $rate->{$i} / $total * 100 %>%)</p>
% }
<hr>
% for my $i (sort keys %$by_genre) {
<p><b><%= $i %> rating:</b> <%= $by_genre->{$i} %> (<%= sprintf '%.2f', $by_genre->{$i} / $total * 100 %>%)</p>
% }
@@ layouts/default.html.ep
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/style.css">
<title><%= title %></title>
<style>
body {
color: #414A4C;
}
a:link, a:visited, a:hover, a:active, a:focus {
color: #414A4C;
}
.dark {
background-color: #414A4C;
color: #DDD;
}
.dark a {
color: #DDD;
}
@media screen and (max-width: 800px) and (orientation: landscape) {
html {
transform: rotate(-90deg);
transform-origin: left top;
width: 100vh;
height: 100vw;
overflow-x: hidden;
position: absolute;
top: 100%;
left: 0;
}
}
@media screen and (max-width: 800px) {
body {
display: block;
width: 100%;
margin-left: auto;
margin-right: auto;
text-align: center;
}
}
</style>
</head>
<body>
<%= content %>
<p></p>
<div id="footer" class="text-secondary">
<hr>
<a href="https://github.com/ology/audio-player">audio-player3</a>
built by <a href="http://gene.ology.net/">Gene</a>
with <a href="https://www.perl.org/">Perl</a>,
<a href="https://mojolicious.org/">Mojolicious</a>
and <a href="https://jquery.com/">jQuery</a>
</div>
</body>
</html>