2008年4月4日金曜日

iTunesのプレイリストをSO905iへ

m4aファイルに3gpメタデータを埋め込むことができたので,iTunesのプレイリストからmicroSDカードへのAACファイルの書き込み,メタデータ埋め込みを自動化してみる。iTunesのプレイリストに登録された曲の取得にはScriptingBridgeを使う。
(1) iTunesのプレイリスト"SO905i"からScriptingBridgeを通してtrack一覧を取得,(2) 各ファイルの拡張子を.m4aから.3gpに変えながらmicroSDにコピー,(3)3gpメタデータを埋め込む,という手順でrubyスクリプトを作ってみた。

#!/usr/bin/env ruby

# configuration
LIB_NAME = 'ライブラリ'
PLAYLIST_NAME = 'SO905i'
DEST_DIR = '/Volume/Untitled/MUSIC'
ITUNES_BASE = '/Users/nishio/Music/iTunes/iTunes Music/'
CMD_M4A = '/Users/nishio/bin/AtomicParsley'
CMD_3GP = '/Users/nishio/bin/AtomicParsley_3gp'

# load libraries
require 'fileutils'
require 'pathname'
require 'osx/cocoa' # load cocoa library.
include OSX # setup for scripting bridge.
OSX.require_framework 'ScriptingBridge'

###
### convert m4a metadata to 3gp metadata
###
def m4a_to_3gp(file)
file = file.gsub(/"/) {|s| '\\' + s} # escape double quote
# parse .m4a atom
h = Hash.new
open("| #{CMD_M4A} \"#{file}\" -t") { |f|
while line = f.gets
line =~ /Atom "(.*)".* contains: (.*)/
h[$1] = $2.gsub(/"/) {|s| '\\' + s} # escape double quote
end
}

# put .3gp atom
h["trkn"] =~ /([0-9]*) of [0-9]*/
num = $1
args = "--3gp-title \"#{h["\302\251nam"]}\" lang=jpn --3gp-performer \"#{h["\302\251ART"]}\" lang=jpn --3gp-album \"#{h["\302\251alb"]}\" track=#{num} lang=jpn --3gp-genre \"#{h["\302\251gen"]}\" lang=jpn --3gp-year '#{h["\302\251day"]}' --overWrite"
system("#{CMD_3GP} \"#{file}\" #{args}")
end

######################################################################
# main routine begins here.

iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
iTunes.sources.each do |source|
next unless source.name == LIB_NAME
source.userPlaylists.each do |playlist|
next unless playlist.name == PLAYLIST_NAME
base = Pathname.new(ITUNES_BASE)
playlist.fileTracks.each do |track|
next unless track.enabled?

path = track.location.path
path_name = Pathname.new(path)
ext_name = File.extname(path)
dst_name = DEST_DIR + path_name.relative_path_from(base)
dst_dir = File.dirname(dst_name)

# create destination directories if not exists.
if !FileTest.exist?(dst_dir) then
puts "make directory: #{dst_dir}"
FileUtils.mkdir_p(dst_dir)
end

# copy a file
puts "copy file: #{dst_name}"
case ext_name
when '.m4a' then
dst_name = File.join(dst_dir, File.basename(dst_name, ext_name) + '.3gp')
FileUtils.cp(path, dst_name)
m4a_to_3gp(dst_name)
else
FileUtils.cp(path, dst_name)
end
end
end
end

0 件のコメント: