LoginSignup
3
0

More than 5 years have passed since last update.

AppleScriptとPHPで現在iTunesで再生中の楽曲のアルバム画像を検索、取得する

Last updated at Posted at 2017-11-30

まずAppleScriptで再生中の曲の曲名とアーティスト名を取得する。

get_search_word
tell application "iTunes"
    set trackName to name of current track
    set trackArtist to artist of current track
    return trackName & " " & trackArtist & " アルバム画像"
end tell

上のAppleScriptで取得した情報をGoogle Custom Search APIを使って検索する。
APIから帰ってきたJSONに画像のURLが含まれているのでそれを保存&openコマンドで開く

<?php
//API情報
$api_key = "<Google Custom Search APIのAPIKey>";
$custom_search_engine = "<Googleカスタム検索エンジンID>";
//ページ数
$start = 1;
//何枚目の画像を使用するか(デフォルトは1枚目)
$img_num = 0;
//AppleScriptでiTunesで再生中の曲名とアーティスト名を取得
//AppleScriptへのpathは適宜変更
$word = exec("osascript ./get_search_word.scpt");
$search_word = urlencode($word);

//ローディングメッセージ表示
$word_array = explode(" ",$word);
echo $word_array[0]."のアルバム画像を取得中...(keyword: 「".$word."」)";
$start_time = microtime(true);

//APIのURL
$api_url = "https://www.googleapis.com/customsearch/v1?key=".$api_key."&cx=".$custom_search_engine."&q=".$search_word."&searchType=image&start=".$start;
$re_json = @file_get_contents($api_url);
$dec_json = json_decode($re_json,true);
//usageLimitsで403帰ってきてNULLだったら終了
if (!$re_json) {
  echo "\nAPIリクエストエラー";
  exit;
}
//($img_num)枚目の画像のURL
$img_url = $dec_json["items"][$img_num]["link"];
//SSL無効に(一部サイトでエラー出た)
$options['ssl']['verify_peer']=false;
$options['ssl']['verify_peer_name']=false;
$data = file_get_contents($dec_json["items"][$img_num]["link"], false, stream_context_create($options));
//ファイルpath定義
$name = "img";
$img_file_name = "./tmp/".$name.".jpg";
//保存
if (file_put_contents($img_file_name,$data)) {
  //画像をopenコマンドで開く
  exec("open ".$img_file_name);
}
//終了メッセージを表示
$end_time = microtime(true);
$elapsed_time = round($end_time - $start_time, 3);
echo "\n取得完了(".$elapsed_time."s)";
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0