-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbgm.rb
106 lines (82 loc) · 1.53 KB
/
bgm.rb
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
Bundler.require
require "tempfile"
require "open-uri"
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
def info(item)
puts "#{item['artistName']} - #{item['trackName']} #{item['collectionViewUrl']}"
end
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
def async?
@async
end
def async!
@async = true
end
def shuffle!
@shuffle = true
end
def rate(value)
@rate = value
end
def player(value)
@player = value
end
protected
def lookup(track)
ITunesSearchAPI.lookup(:id => track['trackId'], :country => "JP")
end
def download(item)
content = open(item['previewUrl']).read
file = Tempfile.new('bgm')
file.print content
file.close
file
end
end
trap(:INT) { exit }
term = ARGV.shift
unless term
warn "usage: #{ $0 } TERM"
exit 1
end
bgm = BGM.new
while ARGV.length > 0
v = ARGV.shift
if v == '--async'
bgm.async!
end
if v == '--shuffle'
bgm.shuffle!
end
if v == '--rate'
bgm.rate(ARGV.shift)
end
if v == '--player'
bgm.player(ARGV.shift)
end
end
puts "provided courtesy of iTunes"
bgm.each(term) {|track|
bgm.info track
bgm.play track
}
sleep 1