前段时间写了一篇c#解析Lrc歌词文件,对lrc文件进行解析,支持多个时间段合并。本文借下载歌词文件来探讨一下同步和异步方法。
Lrc文件在网络上随处可见,我们可以通过一些方法获取,最简单的就是别人的接口,如:
http://geci.me/api/lyric/不得不爱 返回下面的json,这样我们就很容易得到歌词文件了。
{ "count": 2, "code": 0, "result": [ { "aid": 2727794, "lrc": "http://s.geci.me/lrc/327/32793/3279317.lrc", "song": "不得不爱", "artist_id": 2, "sid": 3279317 }, { "aid": 3048347, "lrc": "http://s.geci.me/lrc/371/37129/3712941.lrc", "song": "不得不爱", "artist_id": 2, "sid": 3712941 } ] }
在c#解析Lrc歌词文件中我们创建了Lrc类,我们继续在该类中添加方法。
同步下载实现
创建SearchLrc静态方法,该方法实现对歌词的搜索:首先查看本地文件夹(我的文件夹是D:\lrc\)是否存在lrc文件,如果不存在就下载lrc文件,返回Lrc对象。
public static Lrc SearchLrc(string musicName) { string path = @"D:\lrc\" + musicName + ".lrc"; if (System.IO.File.Exists(path)) { return InitLrc(path); } else { return DownloadLrc(musicName, path); } }
下载歌词利用WebClient,首先用DownloadString方法将获取json,再利用JavaScriptSerializer反序列化为自定义对象,这样就得到了lrc文件的url,最后通过url将lrc文件下载到本地,再调用InitLrc方法返回Lrc对象。
public class TempJosnMain { public int count { get; set; } public int code { get; set; } public List<TempJsonChild> result { get; set; } } public class TempJsonChild { public int aid { get; set; } public string lrc { get; set; } public string song { get; set; } public int artist_id { get; set; } public int sid { get; set; } } static Lrc DownloadLrc(string musicName, string path) { if (musicName.Contains("-")) musicName = musicName.Split('-')[1].Trim(); string url = "http://geci.me/api/lyric/" + musicName; WebClient wc = new WebClient(); string json = wc.DownloadString(url); JavaScriptSerializer js = new JavaScriptSerializer(); TempJosnMain res = js.Deserialize<TempJosnMain>(json); if (res.count > 0) { wc.DownloadFile(new Uri(res.result[0].lrc), path); wc.Dispose(); return InitLrc(path); } return new Lrc(); }