Parse m3u Music link file

Source: Internet
Author: User

M3U is essentially not an audio file, it is a list file of audio files and is a plain text file. You download it to open it, and the playback software does not play it, but instead finds the network address for online playback based on its record.

Let's parse the music network address in the M3U file:

First, the interface is as follows: The interface is very simple, an input box (enter a m3u file link), and then parse, start and stop buttons. After parsing is complete, the Start button gets the focus

Play music parsed from a m3u file


Second, the XML file is as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ".        Mainactivity "> <edittext android:layout_width=" fill_parent "android:layout_height=" Wrap_content "        Android:id= "@+id/m3utextpath"/> <linearlayout android:layout_width= "Fill_parent"        android:layout_height= "wrap_content" android:orientation= "horizontal" android:layout_margintop= "60dip" > <button android:layout_width= "wrap_content" android:layout_height= "Wrap_conte NT "android:id=" @+id/parse "Android:onclick= "Mainclick" android:text= "parsing"/> <button android:layout_width= "Wrap_conte NT "android:layout_height=" Wrap_content "android:id=" @+id/start "android:onclick=" Mainclick "a ndroid:text= "Start"/> <button android:layout_width= "Wrap_content" Android:layout_            height= "Wrap_content" android:id= "@+id/stop" android:onclick= "Mainclick" android:text= "Terminate"        /> <button android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:id= "@+id/pausepull" android:onclick= "Mainclick" android:text= "Pull parse"/> </lin Earlayout> <!--the ListView with ID @id/android:list is a customized list layout, and if not, the default layout--><listview android:id= "@id/ Android:list "android:layout_width=" fill_parent "android:layout_height=" wrap_content "android:background=" #00FF00 "Android:drawselectorontop=" false "android:layout_margintop= "100dip"/> <!--when there is no data in the ListView, the view with the ID @id/android:empty is displayed--><textview Android:id= "@id/android:empty" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android: Textcolor= "#FF0000" android:text= "No data" android:gravity= "Center_vertical|center_horizontal" Android:layout_ margintop= "110dip"/></relativelayout>
Third, activity

Package Com.example.m3upulltest;import Java.io.ioexception;import Java.io.inputstream;import java.util.List;import Com.example.parseutil.m3uparser;import Com.example.parseutil.person;import Com.example.parseUtil.netXmlPause; Import Android.app.listactivity;import android.media.mediaplayer;import android.os.bundle;import android.util.Log; Import Android.view.menu;import android.view.view;import android.widget.arrayadapter;import Android.widget.Button; Import Android.widget.edittext;import Android.widget.listadapter;import Android.widget.toast;public class Mainactivity extends Listactivity {/** * Android support play audio on the network * access to the network of audios, we need to get the stream via HTTP * This may involve the icy protocol.  Icy extension of HTTP protocol * However, sites on the network often do not allow us to access their audio streams directly * We need an intermediate file to point to the address of the audio stream we need to enable third party software to play. * For icy flow, it is a pls file or a m3u file * pls corresponds to the MIME type: AUDIO/X-SCPLS * m3u corresponding MIME type is: Audio/x-mpegurl * * Although Android provides support for icy stream  , but it does not provide an out-of-the-box method to parse m3u or pls files * So, in order to play the audio stream on the network, we need to implement the parsing of these files ourselves * m3u file is actually an index file of an audio stream, he points to the path of the audio stream to play. * @author Administrator * *///private EditText m3utextpath;private Button btnparse, Btnplay, btnstop;            Private EditText Editurl;            Private MediaPlayer player;            Private list<string> pathList; private int currposition = 0; Records the currently played media file's index protected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Editurl = (EditText) Findviewbyid (r.id.m3utextpath); btnparse = (Button)          This.findviewbyid (R.id.parse);          Btnplay = (Button) This.findviewbyid (R.id.start);                    Btnstop = (Button) This.findviewbyid (r.id.stop);  Editurl.settext ("http://pubint.ic.llnwd.net/stream/pubint_kmfa.m3u");           Inputmethodmanager IMM = (inputmethodmanager) this.getsystemservice (Input_method_service);          Btnplay.setenabled (FALSE);                    Btnstop.setenabled (FALSE);          Player = new MediaPlayer ();  Player.setoncompletionlistener (New Mediaplayer.oncompletionlistener () {                          public void Oncompletion (MediaPlayer player) {//This method triggers when MediaPlayer play () finishes executing                  Player.stop ();                  Player.reset (); if (Pathlist.size () > Currposition+1) {currposition++;//Go to next Preparetoplay (                  );                    }              }          });  Player.setonpreparedlistener (New Mediaplayer.onpreparedlistener () {//buffer complete execution public void Onprepared (MediaPlayer arg0) {//This method triggers prepare when MediaPlayer btnstop.setenabled () is executed (                  true);                                    Player.start (); When a song is finished, execute Oncompletionlistener's Oncompletion Method}}); }/** * Play Music */private void Preparetoplay () {try {//Get the path of the current audio stream after we need to set it through MediaPlayer Setdatasource, and then      Call Prepareasync () to complete the cache load String path = Pathlist.get (currposition);        Player.setdatasource (path); The reason for using Prepareasync is because the method is asynchronous because the access audio stream is a network operation that takes a long time to buffer and prepare for playback, so that the user interface can get stuck.//When the method executes, it               Executes the onprepared () method of the Onpreparedlistener. Player.prepareasync ();//async thread avoids card-dead} catch (IllegalArgumentException e) {//TODO Auto-gen          Erated Catch block E.printstacktrace ();          } catch (IllegalStateException e) {//TODO auto-generated catch block E.printstacktrace ();          } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }}/** * Button event * @throws Exception */public void Mainclick (View v) throws Exception{switch (V.getid ()) {   Case r.id.parse://completed parsing//progress = Progressdialog.show (This, "prompt", "parsing, please later ...");               Progress.show ();              String URL = null; if (editurl.gettext () = null) {URL = edIturl.gettext (). toString (); } if (URL! = null &&!url.trim (). Equals ("")) {pathList = M3uparser.parsestringfromurl                  (URL); ListAdapter adapter = new Arrayadapter<string> (this, Android.                  R.layout.simple_list_item_1, pathList);                  This.setlistadapter (adapter);              Btnplay.setenabled (TRUE);              }else{Toast.maketext (This, "Please enter the correct m3u file access address", Toast.length_long). Show ();              } break;case R.id.start://Here playback is from the first beginning of the btnplay.setenabled (false);              Btnparse.setenabled (FALSE);              this.currposition = 0;              if (pathList! = null && pathlist.size () > 0) {preparetoplay ();                      } break;              Case R.id.stop:player.pause ();              Btnplay.setenabled (TRUE);              Btnstop.setenabled (FALSE);         Break         Default:break;}} Menu public boolean oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the action bar if it is present . Getmenuinflater (). Inflate (R.menu.main, menu); return true;}}
Third, parse the code:

Package Com.example.parseutil;import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.util.arraylist;import Java.util.list;import Org.apache.http.HttpResponse;      Import Com.example.httpserver.httpconnect;public class M3uparser {/** * return list<string> type * @param URL          * @return */public static list<string> parsestringfromurl (String url) {list<string> resultlist = null;          HttpResponse res = httpconnect.getresponsefromurl (URL);                  try {if (res! = null) {resultlist = new arraylist<string> ();                  InputStream in = Res.getentity (). getcontent ();                  BufferedReader reader = new BufferedReader (new InputStreamReader (in));                  String line = ""; while (line = Reader.readline ()) = null) {if (Line.startswith ("#")) {//here is Me Tadata Information}else if (Line.length () &Gt 0 && Line.startswith ("http//")) {//Here is a pointer to the audio stream path Resultlist.ad                      D (line);              }} in.close ();          }} catch (Exception e) {e.printstacktrace (); } return resultlist;      }/** * Resolves from the specified URL and returns a list containing FilePath objects * FilePath encapsulates each audio path. * @param URL * @return */public static list<filepath> parsefromurl (String url) {list&lt ;          Filepath> resultlist = null;          HttpResponse response = httpconnect.getresponsefromurl (URL);                  try {if (response! = null) {resultlist = new arraylist<m3uparser.filepath> ();                  InputStream in = Response.getentity (). getcontent ();                  BufferedReader reader = new BufferedReader (new InputStreamReader (in));                  String line = ""; while (line = Reader.readline ())! = NuLL) {if (Line.startswith ("#")) {//Here is metadata information}else I                           F (line.length () > 0 && line.startswith ("http//")) {//Here is a pointer to the audio stream path                          FilePath FilePath = new FilePath (line);                      Resultlist.add (FilePath);              }} in.close ();          }} catch (Exception e) {e.printstacktrace ();      } return resultlist;                    }//Parsed entity object static class filepath{private String FilePath;          Public FilePath (String FilePath) {this.filepath = FilePath;          } public String GetFilePath () {return filePath;          } public void SetFilePath (String filePath) {this.filepath = FilePath; }      }     }






Parse m3u Music link file

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.