ソースコードを読んでみた - bgm.rb

ターミナルから簡単に曲を聞けるbgm.rbというのを作った - hitode909の日記

Rubyのgemのソースコードを効率的に読む方法を使ってbgm.rbのコードをざっと読んでみました。bundlerは実行環境なのでちょっとずつ挙動を変えながらコードを読めるのがよいです。2015年で今更だけどbundler本当に便利だ・・。

bundle exec -- ruby bgm.rb "椎名林檎"

しながらコード読みました。

f:id:tuto0621:20150130231222p:plain

bgm.rb

bgm.rb

本体です。BGMクラスの定義が上部にBGMクラスのインスタンスを使うメイン処理が下部にあります。

BGMクラスは大きく分けて

  • キーワードにマッチする楽曲データを取得
  • 楽曲データから音楽ファイル(m4a)のURLを取得、ダウンロード
  • ダウンロードした音楽ファイルを再生(デフォルトはafplay)

OSXってafplayっていうコマンドで音楽再生出来るのですね。

  def play(item)
    file = download(item)

    command = "#{@player || 'afplay'} #{file.path}"

    if @rate
      command += " --rate #{ @rate } "
    end

    if async?
      command += " &"
    end

    system command
  rescue Interrupt
    nil
  end

楽曲データの取得は'itunes-search-api'というGemに任せているようなのでそちらも読んでみます。

class BGM
  def each(term)
    tracks = ITunesSearchAPI.search(term: term, country: "JP", media: "music", limit: async? ? 10 : 200)
    tracks.shuffle! if @shuffle
    tracks.each{|track|
      yield lookup track
    }
  end
  .
  .

itunes-search-api gem

rlivsey/itunes-search-api

HTTPartyというgemを使ってAPIを定義しているようです。おそらくgetベースの特定のURLを叩くとjsonが返ってくるAPIのようです。

require 'httparty'

class ITunesSearchAPI
  include HTTParty
  base_uri 'http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa'
  format :json

  class << self
    def search(query={})
      get("/wsSearch", :query => query)["results"]
    end

    def lookup(query={})
      if results = get("/wsLookup", :query => query)["results"]
        results[0]
      end
    end
  end
end

README.rdocを読んでみるとiTunes APIのドキュメントへのリンクがありました。

= ITunesSearchAPI

Ruby interface to the ITunes Search API

http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html

得られた知見

  • iTunesの楽曲データを取得したい時はitunes-search-api gemを使う
  • ダウンロードした音楽データの再生にはOSXだとafplay
  • HTTPartyというgemを使うとAPIのラッパークラスを簡単に書ける