Implementation features:
Realize the download function of music lyrics (download music, download the corresponding lyrics)
The downloaded lyrics are not currently in the player and can be viewed through the file browser.
Follow-up Will blog, will implement local music lyrics download and have downloaded music scanning function.
Because, there is no own server, so the network music all related functions (including search music, download music, download lyrics) can not guarantee the timeliness, suggestions, as soon as possible to download and practice; If you download, already because I collected the server change rule, please give me a message, if can solve, I will present a new source when I am free.
Until the current source download:
http://download.csdn.net/album/detail/3105
(Latest, please download the last one, this post corresponds to version 2.0; lyrics Download only modified downloadutils, so download 1.9, modify the Downloadutils, is also possible; If you need to step through the process, please download all)
Welcome to Mobile development enthusiasts Exchange: mine is Iwanghang
In addition, I intend to start looking for a job, if Shenyang or the surrounding city company is interested, please contact me.
Achieve results
The implementation code is as follows:
Downloadutils as follows:
package com.iwanghang.drmplayer.utils;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import com.iwanghang.drmplayer.vo.SearchResult;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.xml.parsers.ParserConfigurationException;
/**
* Created by iwanghang on 16/5/3.
* Internet music download tools
*/
public class DownloadUtils {
private static final String DOWNLOAD_URL = "/ download? _o =% 2Fsearch% 2Fsong";
private static final int SUCCESS_LRC = 1; // The lyrics were downloaded successfully
private static final int FAILED_LRC = 2; // Failed to download lyrics
private static final int SUCCESS_MP3 = 3; // Successfully downloaded songs
private static final int FAILED_MP3 = 4; // Failed to download songs
private static final int GET_MP3_URL = 5; // Get music successfully
private static final int GET_FAILED_MP3_URL = 6; // Failed to get music
private static final int MUSIC_EXISTS = 7; // When downloading, the music already exists
private static DownloadUtils sInstance;
private OnDownloadListener mListener;
private ExecutorService mThreadPool;
/**
* Set callback listener object
* @param mListener
* @return
*/
public DownloadUtils setListener (OnDownloadListener mListener) {
this.mListener = mListener;
return this;
}
// Get an example of the download tool
public synchronized static DownloadUtils getsInstance () {
if (sInstance == null) {
Try {
sInstance = new DownloadUtils ();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
return sInstance;
}
/**
* Download specific business methods
* @throws ParserConfigurationException
*/
private DownloadUtils () throws ParserConfigurationException {
mThreadPool = Executors.newSingleThreadExecutor ();
}
public void download (final SearchResult searchResult) {
final Handler handler = new Handler () {
@Override
public void handleMessage (Message msg) {
switch (msg.what) {
case SUCCESS_LRC:
if (mListener! = null) mListener.onDowload ("Lyrics downloaded successfully");
Break;
case FAILED_LRC:
if (mListener! = null) mListener.onFailed ("Lyrics download failed");
Break;
case GET_MP3_URL:
System.out.println ("GET_MP3_URL:" + msg.obj);
downloadMusic (searchResult, (String) msg.obj, this);
Break;
case GET_FAILED_MP3_URL:
if (mListener! = null) mListener.onFailed ("The download failed, the song is paid or VIP type");
Break;
case SUCCESS_MP3:
if (mListener! = null) mListener.onDowload (searchResult.getMusicName () + "Downloaded");
String url = Constant.MIGU_URL + searchResult.getUrl ();
System.out.println ("download lrc:" + url);
downloadLRC (url, searchResult.getMusicName (), searchResult.getArtist (), this);
Break;
case FAILED_MP3:
if (mListener! = null) mListener.onFailed (searchResult.getMusicName () + "Download failed");
Break;
case MUSIC_EXISTS:
if (mListener! = null) mListener.onFailed ("Music already exists");
Break;
}
}
};
getDownloadMusicURL (searchResult, handler);
}
// Get URL for downloading lyrics
private void getDownloadLrcURL (final SearchResult searchResult, final Handler handler) {
mThreadPool.execute (new Runnable () {
@Override
public void run () {
//http://music.baidu.com/search/lrc?key=%E6%9C%89%E5%BF%83%E4%BA%BA%20G.EM%E9%82%93%E7%B4 % AB% E6% A3% 8B
//"http://music.baidu.com/search/lrc?key= "+ song name +" "+ artist
//System.out.println ("searchResult.getUrl () =" + searchResult.getUrl ());
// String [] aa = searchResult.getUrl (). Split ("/");
// String sn = aa [5];
//System.out.println("song number = "+ sn);
// The Url copied from the browser looks like this, "http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";
// Chinese characters are encoded by UTF8, such as ice rain ==% E5% 86% B0% E9% 9B% A8;
// tested Get page Use "http://music.baidu.com/search?key=ice rain"; unable to open correct connection
// For example, use URLEncoder.encode to convert to utf8
// Actual use Get page Use "http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";
Try {
String musicName = URLEncoder.encode (searchResult.getMusicName (), "utf8");
String artistName = URLE
ncoder.encode (searchResult.getArtist (), "utf8");
// String url = Constant.BAIDU_LRC_SEARCH_HEAD + searchResult.getMusicName () + "" + searchResult.getArtist ();
String url = Constant.BAIDU_LRC_SEARCH_HEAD + musicName + "+" + artistName;
System.out.println ("Lyrics download page url =" + url);
Document doc = Jsoup.connect (url) .userAgent (Constant.USER_AGENT) .timeout (6000) .get ();
//System.out.println("Lyrics download page doc: "+ doc);
Elements lrcUrls = doc.select ("span.lyric-action");
System.out.println (lrcUrls);
for (int i = 0; i <lrcUrls.size (); i ++) {
Elements urlsa = lrcUrls.get (i) .getElementsByTag ("a");
System.out.println ("tag a urlsa:" + urlsa);
for (int a = 0; i <urlsa.size (); a ++) {
System.out.println ("----" + urlsa.get (a) .toString ());
String urla = urlsa.get (a) .toString ();
System.out.println ("-----" + urla);
// ----- <a class="down-lrc-btn {'href':'/data2/lrc/14488216/14488216.lrc' }" href="#"> Download LRC lyrics </a>
if (urla.indexOf ("'href': '")> 0) {
String [] uu = urla.split ("'href': '");
System.out.println ("uu1:" + uu [1]);
// uu1: /data2/lrc/14488216/14488216.lrc '} "href =" # "> Download LRC lyrics </a>
String [] uuu = uu [1] .split (". Lrc");
System.out.println ("uuu0:" + uuu [0]);
// uuu0: / data2 / lrc / 14488216/14488216
String result = "http://music.baidu.com" + uuu [0] + ".lrc";
System.out.println ("result:" + result);
// result: http://music.baidu.com/data2/lrc/14488216/14488216.lrc
Message msg = handler.obtainMessage (SUCCESS_LRC, result);
msg.sendToTarget ();
Break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
handler.obtainMessage (FAILED_LRC) .sendToTarget ();
}
}
});
}
// Get URL to download music
private void getDownloadMusicURL (final SearchResult searchResult, final Handler handler) {
mThreadPool.execute (new Runnable () {
@Override
public void run () {
//http://music.migu.cn/#/album/1003215276
// 1003215279
//http://music.migu.cn/order/1003215279/down/self/P2Z3Y12L1N2/3/001002A/1003215279
System.out.println ("searchResult.getUrl () =" + searchResult.getUrl ());
String [] aa = searchResult.getUrl (). Split ("/");
String sn = aa [5];
System.out.println ("song number =" + sn);
String url = Constant.MIGU_DOWN_HEAD + sn + Constant.MIGU_DOWN_FOOT;
System.out.println ("song download page url =" + url);
Try {
Document doc = Jsoup.connect (url) .userAgent (Constant.USER_AGENT) .timeout (6000) .get ();
//System.out.println(doc);
System.out.println ("doc.toString () =" + doc.toString ());
String [] bb = doc.toString (). Split ("song"); // The download page source code is divided according to "song"
for (int i = 0; i <bb.length; i ++) {
System.out.println ("bb [" + i + "] =" + bb [i]);
if (bb [i] .indexOf ("mp3? msisdn")> 0) {
System.out.println ("mp3? Msisdn =" + bb [i]);
String initMp3Url = bb [i]; // initMp3Url Initial Mp3 download link, as follows
// mp3? msisdn = ":" http://tyst.migu.cn/public/ringmaker01 October 31 Chinese extension / file / full format / 9000 songs / full song audition / Mp3_128_44_16 / days passed together-Andy Lau .mp3? msisdn \ u003d7b609763f0ff ","
String [] arrayHttp = initMp3Url.split ("http"); // The initial Mp3 download link is divided according to "http"
String [] arrayMp3 = arrayHttp [1] .split (". Mp3"); // Split arrayHttp according to ".mp3"
String result = "http" + arrayMp3 [0] + ".mp3"; // "http" and ".mp3" with the division removed, combined back
System.out.println ("result");
// String result = "http://tyst.migu.cn/public/ringmaker01 October 31st Chinese postponed / file / full format / 9000 songs / full song audition / Mp3_128_44_16 / days passed together-Andy Lau.mp3" ;
Message msg = handler.obtainMessage (GET_MP3_URL, result);
msg.sendToTarget ();
}
}
} catch (IOException e) {
e.printStackTrace();
handler.obtainMessage (GET_FAILED_MP3_URL) .sendToTarget ();
}
}
});
}
// Download lyrics
private void downloadLRC (final String url, final String musicName, final String artistName, final Handler handler) {
mThreadPool.execute (new Runnable () {
@Override
public void run () {
// The Url copied from the browser looks like this, "http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";
// Chinese characters are encoded by UTF8, such as ice rain ==% E5% 86% B0% E9% 9B% A8;
// tested Get page Use "http://music.baidu.com/search?key=ice rain"; unable to open correct connection
// For example, use URLEncoder.encode to convert to utf8
// Actual use Get page Use "http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";
Try {
String musicNameEn = URLEncoder.encode (musicName, "utf8");
String artistNameEn = URLEncoder.encode (artistName, "utf8");
// String url = Constant.BAIDU_LRC_SEARCH_HEAD + searchResult.getMusicName () + "" + searchResult.getArtist ();
String url = Constant.BAIDU_LRC_SEARCH_HEAD + musicNameEn + "+" + artistNameEn;
System.out.println ("Lyrics download page url =" + url);
Document doc = Jsoup.connect (url) .userAgent (Constant.USER_AGENT) .timeout (6000) .get ();
//System.out.println("Lyrics download page doc: "+ doc);
Elements lrcUrls = doc.select ("span.lyric-action");
System.out.println (lrcUrls);
for (int i = 0; i <lrcUrls.size (); i ++) {
Elements urlsa = lrcUrls.get (i) .getElementsByTag ("a");
System.out.println ("tag a urlsa:" + urlsa);
for (int a = 0; a <urlsa.size (); a ++) {
//System.out.println("---- "+ urlsa.get (a) .toString ());
String urla = urlsa.get (a) .toString ();
System.out.println ("-----" + urla);
// ----- <a class="down-lrc-btn {'href':'/data2/lrc/14488216/14488216.lrc' }" href="#"> Download LRC lyrics </a>
if (urla.indexOf ("'href': '")> 0) {
String [] uu = urla.split ("'href': '");
System.out.println ("uu1:" + uu [1]);
// uu1: /data2/lrc/14488216/14488216.lrc '} "href =" # "> Download LRC lyrics </a>
String [] uuu = uu [1] .split (". Lrc '");
System.out.println ("uuu0:" + uuu [0]);
// uuu0: /data2/lrc/246970367/246970367.lrc
String lrcDwonUrl = "http://music.baidu.com" + uuu [0] + ".lrc";
System.out.println ("lrcDwonUrl:" + lrcDwonUrl);
// result: http://music.baidu.com/data2/lrc/14488216/14488216.lrc
File LrcDirFile = new File (Environment.getExternalStorageDirectory () + Constant.DIR_LRC);
System.out.println ("LrcDirFile:" + LrcDirFile);
if (! LrcDirFile.exists ()) {
LrcDirFile.mkdirs ();
}
String target = LrcDirFile + "/" + musicName + ".lrc";
System.out.println ("lrcDwonUrl:" + lrcDwonUrl);
System.out.println ("target:" + target);
File fileTarget = new File (target);
if (fileTarget.exists ()) {
handler.obtainMessage (MUSIC_EXISTS) .sendToTarget ();
return;
} else {
OkHttpClient client = new OkHttpClient ();
Request request = new Request.Builder (). Url (lrcDwonUrl) .build ();
Response response = client.newCall (request) .execute ();
if (response.isSuccessful ()) {
PrintStream ps = new PrintStream (new File (target));
byte [] bytes = response.body (). bytes ();
ps.write (bytes, 0, bytes.length);
ps.close ();
handler.obtainMessage (SUCCESS_LRC, target) .sendToTarget ();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
// Download MP3
private void downloadMusic (final SearchResult searchResult, final String url, final Handler handler) {
mThreadPool.execute (new Runnable () {
@Override
public void run () {
File musicDirFile = new File (Environment.getExternalStorageDirectory
() + Constant.DIR_MUSIC);
if (! musicDirFile.exists ()) {
musicDirFile.mkdirs ();
}
String mp3url = url;
// String mp3url = "http://tyst.migu.cn/public/600902-2008430/tone/2008/09/10/September/April 2008 Global 106 songs / Ring tones / 7_mp3-128kbps / waiting for you Wait till my heartache-Jacky Cheung.mp3 ";
String target = musicDirFile + "/" + searchResult.getMusicName () + ".mp3";
System.out.println (mp3url);
System.out.println (target);
File fileTarget = new File (target);
if (fileTarget.exists ()) {
handler.obtainMessage (MUSIC_EXISTS) .sendToTarget ();
return;
} else {
// Use OkHttpClient component
OkHttpClient client = new OkHttpClient ();
Request request = new Request.Builder (). Url (mp3url) .build ();
System.out.println (request);
Try {
Response response = client.newCall (request) .execute ();
if (response.isSuccessful ()) {
PrintStream ps = new PrintStream (fileTarget);
byte [] bytes = response.body (). bytes ();
ps.write (bytes, 0, bytes.length);
ps.close ();
handler.obtainMessage (SUCCESS_MP3) .sendToTarget ();
}
} catch (IOException e) {
e.printStackTrace();
handler.obtainMessage (FAILED_MP3) .sendToTarget ();
}
}
}
});
}
// Custom download event listener
public interface OnDownloadListener {
public void onDowload (String mp3Url);
public void onFailed (String error);
}
}
Android development Local and network MP3 music Player (15) network music and lyrics download function realization