获取当前Spotify播放歌曲的歌词

背景

标题是お盆休み之前给自己布置的作业。

很多时候上班带着耳机写代码,听到不错的歌曲很自然而然想去找歌词。Spotify这种垃圾东西,有歌词的歌曲又极其少,而且当你在termnial敲代码的时候自然不想离开termial。
这个时候,敲个命令就能显示当前播音乐的歌词多好。

解决方案设计

想要获取当前的歌曲的歌词,自然先得获取当前的歌曲名字(track)和专辑名(album)以及歌手名(artist)。

乍一想难上天啊,如果spotify不提供什么机制的话,这个就是强制进程通信啊。

还好,spotify有web console这种东西可以支持操作现在的播放设备。这里就不废话了,没有采用的理由是access token的默认寿命只有1小时。🤣

其实OS X提供了一个很牛逼的工具可以让我们达到获取歌曲名,歌手以及专辑名的方法。那就是osascript

1
2
3
4
5
6
➜  my_blog git:(master) ✗ osascript -e 'tell application "Spotify" to artist of current track as string'
Park Boram
➜ my_blog git:(master) ✗ osascript -e 'tell application "Spotify" to name of current track as string'
Will Be Fine
➜ my_blog git:(master) ✗ osascript -e 'tell application "Spotify" to album of current track as string'
Will Be Fine

wow,crazy. 接下来就是找个搜歌词的接口把这些塞进去就是了。

Genius 这个网站提供了搜歌词的接口,注册之后可以免费使用。从搜索的返回结果中找到歌词网页的path,最后用爬虫爬取页面获得歌词即可。

Demo

调用osacript和获取歌词path这些在shell脚本中完成即可。至于爬虫有些麻烦,我用nokogiri写了个ruby脚本,将歌词path作为参数传给ruby脚本处理最后输出歌词。

1
2
3
4
5
6
7
8
9
10
11
12
13
#! /bin/sh

artist=`osascript -e 'tell application "Spotify" to artist of current track as string'`;
track=`osascript -e 'tell application "Spotify" to name of current track as string'`;
album=`osascript -e 'tell application "Spotify" to album of current track as string'`;

lyrics_data=`curl -s "https://api.genius.com/search?q='"$track $artist $album"'" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer your_own_token" `

lyrics_path=`echo $lyrics_data | jq ".response.hits[0].result.path"`

song_title=`echo $lyrics_data | jq ".response.hits[0].result.full_title"`

ruby ./lyrics_parser.rb "$lyrics_path" "$song_title"

ruby 脚本就是个爬虫,最后输出歌词即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
require "nokogiri"
require "open-uri"

url = "https://genius.com#{ARGV[0]}".gsub('"',"")

html = open(url) do |f|
charset = f.charset
f.read
end

doc = Nokogiri::HTML.parse(html, nil, nil)
doc.xpath('//div[@class="lyrics"]').each do |node|
puts ARGV[1] + "\n"
puts node.inner_text
end

运行效果如下。

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
➜  cmd_lyrics ./lyx.sh
supercell
君の知らない物語
https://genius.com/Supercell-kimi-no-shiranai-monogatari-lyrics
"君の知らない物語 (Kimi no Shiranai Monogatari) by ​supercell"



Itsumodoori no aruhi no koto
Kimi wa totsuzen tachiagari itta
"konya hoshi o mi ni yukou"

"tamani wa ii koto iunda ne"
Nante minna shite itte waratta
Akarimonai michi o
Bakamitai ni hashaide aruita
Kakaekonda kodoku ya fuan ni
Oshitsubusarenaiyouni


Makkurana sekai kara miageta
Yozora wa hoshi ga furu youde


Itsu kara darou kimi no koto o
Oikakeru watashi ga ita
Douka onegai
Odorokanaide kiiteyo
Watashi no kono omoi o
....

渣渣渣。

后续

这个世界上本来就不存在一个很好的歌词库。

以上。