Android development Local and network MP3 music Player (15) network music and lyrics download function realization

Source: Internet
Author: User

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.    * Network music Download Tool class */public class Downloadutils {private static final String Download_url = "/download?_o=%2fsearch%2fsong";  private static final int success_lrc = 1;//Download Lyrics success private static final int failed_lrc = 2;//Download lyrics failed private static Final int success_mp3 = 3;//Download song intoREACTIVE private static final int failed_mp3 = 4;//Download song failed private static final int get_mp3_url = 5;//Get music success Private stat IC final int get_failed_mp3_url = 6;//Get music failed private static final int music_exists = 7;//download, music already exists private static do    Wnloadutils sinstance;    Private Ondownloadlistener Mlistener;    Private Executorservice Mthreadpool; /** * Set callback Listener Object * @param mlistener * @return * */Public downloadutils Setlistener (Ondownloadlistener MLIs        Tener) {this.mlistener = Mlistener;    return this;  }//Get instance of download tool public synchronized static Downloadutils Getsinstance () {if (sinstance = = null) {try            {sinstance = new downloadutils ();            } catch (Parserconfigurationexception e) {e.printstacktrace ();    }} return sinstance; }/** * Download the specific business method * @throws parserconfigurationexception */Private Downloadutils () throws Parserconfigu rationexception{mThreadPool = Executors.newsinglethreadexecutor (); public void Download (final SearchResult searchresult) {final Handler Handler = new Handler () {@Over Ride public void Handlemessage (Message msg) {switch (msg.what) {case success_l                       Rc:if (Mlistener! = null) mlistener.ondowload ("lyrics download succeeded");                   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 ("Download failed, the song is a charge 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 the URL to download lyrics private void Getdownloadlrcurl (final SearchResult searchresult, final Handler Handler) {Mthre Adpool.execute (New Runnable () {@Override public void run () {//http://music.baidu.co M/search/lrc?key=%e6%9c%89%e5%bf%83%e4%ba%ba%20g.e.m.%e9%82%93%e7%b4%ab%e6%a3%8b//"http://music.baidu.com/search/lrc?key=" + song name + "+ Singer"                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 is this, "http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";                Chinese characters after UTF8 coding, such as ice rain = =%e5%86%b0%e9%9b%a8;                After the test gets the page uses "http://music.baidu.com/search?key= ice rain"; Unable to open the correct connection//For example, using Urlencoder.encode transcoding, switch to UTF8                The actual use of the Get page using "http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";                    try {String musicname = Urlencoder.encode (Searchresult.getmusicname (), "UTF8");                    String artistname = Urlencoder.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); //-----&Lt;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 = u                                U[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.ob                                Tainmessage (Success_lrc,result); Msg. Sendtotarget ();                            Break }}}} catch (IOException e) {e.printstacktr                    Ace ();                Handler.obtainmessage (FAILED_LRC). Sendtotarget ();    }            }        }); }//Get the URL to download music private void Getdownloadmusicurl (final SearchResult searchresult, final Handler Handler) {mTh Readpool.execute (New Runnable () {@Override public void run () {//HTTP://MUSIC.MIGU.C n/#/album/1003215276//1003215279//http://music.migu.cn/order/1003215279/down/self/p2z3y12l                1n2/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");//download page source code according to "song" Division 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://t YST.MIGU.CN/PUBLIC/RINGMAKER01/10 31st Chinese Extensions/Documents/full Format/9,000 songs/full song audition/mp3_128_44_16/-Andy Lau. mp3?msisdn\ U003d7b609763f0ff "," string[] arrayhttp = Initmp3url.split ("HTTP ");//The initial Mp3 download link according to" http "split string[] arrayMp3 = Arrayhttp[1].split (". mp3 ");//Arrayhttp according to"                            . mp3 "Split String result =" http "+ arraymp3[0] +". mp3 ";//Remove the" http "and". mp3 "from the split and combine them back                            SYSTEM.OUT.PRINTLN ("result"); String result = "HTTP://TYST.MIGU.CN/PUBLIC/RINGMAKER01/10 month 31st Chinese extension/File/full format/9,000 first/full song audition/mp3_128_44_16/                            Together through the days-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 ha Ndler) {Mthreadpool.execute (new Runnable () {@OVerride public void Run () {//The URL copied from the browser is this, "http://music.baidu.com/search?key=%E6%B2%A1%E6%9                C%89 ";                Chinese characters after UTF8 coding, such as ice rain = =%e5%86%b0%e9%9b%a8;                After the test gets the page uses "http://music.baidu.com/search?key= ice rain"; Unable to open the correct connection//For example, using Urlencoder.encode transcoding, switch to UTF8                The actual use of the Get page using "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> S                                Tring[] 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 Fi                                Le (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);                                   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/2008 September/April Global 106 songs/ringtones/7_mp3-128kbps/wait until I 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 {//Using 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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.