December 30, 2004

iTunes Music Library をパースして再生回数を数える

Top20 Albums の集計につかったやっつけスクリプト。

Play Count は累積になっているので「2004年に聞いた」という条件をいれるのは難しいのですが、僕が iTunes を使い始めたのは今年だとおもうので問題なしということに。アルバムをひろってきたあと "Date Added" とかで 2004 年発売の作品でフィルタするのもよいかもしれません。

use strict;
use warnings;
use Encode;
use HTML::Entities;
use Net::Amazon;
use Net::Amazon::Request::Keyword;

my $head = shift || 20;

our $Library = "C:/Documents and Settings/miyagawa/My Documents/My Music/iTunes/iTunes Music Library.xml";
our $DeveloperToken = "D16F26JZ1YEJIY";
our $AssociateID    = "bulknews-22";

open my $fh, "<:encoding(utf-8)", $Library or die "$Library: $!";
my(%count, %data);
while (<$fh>) {
  m!<key>(Artist|Album)</key><string>(.*?)</string>!
    and $data{$1} = HTML::Entities::decode($2);
  m!<key>Play Count</key><integer>(\d+)</integer>!
    and $count{"$data{Artist} - $data{Album}"} += $1;
}

binmode STDOUT, ":encoding(Shift_JIS)";
print qq(<div class="items">\n);
my @keys = (sort { $count{$b} <=> $count{$a} } keys %count)[0..$head-1];
for my $title (@keys) {
  my($artist, $album) = split / - /, $title, 2;
  my $item  = search_aws($artist, $album, "jp", "music-jp");
  printf qq(<div class="item"><a href="%s"><img src="%s" alt="%s - %s" width="130" height="130" border="0" clear="all" /><br />%s</a></div>\n),
    $item->url, $item->ImageUrlMedium,
    $artist, $album, $title;
}
print "</div>\n";

sub search_aws {
    my($artist, $title, $locale, $mode) = @_;
    warn "Searching $artist - $title on Amazon...\n";
    my $attr;
    $attr->{token}  = $DeveloperToken;
    $attr->{locale} = $locale if $locale;
    $attr->{affiliate_id} = $AssociateID;

    my $ua = Net::Amazon->new(%$attr);

    my $keyword = encode("UTF-8", "$artist $title");
    my $req = Net::Amazon::Request::Keyword->new(
        keyword => $keyword,
        mode    => $mode
    );

    my $response = $ua->request($req);
    my $item = ($response->properties())[0];
    return $item;
}
Posted by miyagawa at December 30, 2004 04:09 PM | Permalink | Comments (1) | TrackBack(3)
Comments

iTunes API を使う手もありますね。Win ならそのほうがスマートですね。
このスクリプトは一応Macでも使えるということで。

Posted by: miyagawa on December 30, 2004 09:29 PM
Trackbacks
TrackBack URL for this entry: http://blog.bulknews.net/mt3/mt-tb.cgi/1479
Bush Chemists
Excerpt: iTunes Music Library �...
Weblog: OGQ
Tracked: May 18, 2005 09:07 AM
iTunes Music Library をパースして再生回数を数える
Excerpt: iTunes Music Library �...
Weblog: RVJ
Tracked: May 19, 2005 09:32 AM
http://boy-playing-strip-poker.gu
Excerpt:
Weblog:
Tracked: August 5, 2005 08:15 PM
Post a comment