This article will guide you to do a music player, in the process of doing this Android development example, can help you to further understand and master the learned ListView and other components. In order to have a better learning effect, many of the features we manually implement, such as the music play fast forward and rewind.
First of all, appreciate the interface effect after this example is completed:
First we build the project, the SDK I use is Android2.2, and then it is laid out in XML.
Above is a ListView to display our music list, in the middle is a seekbar can drag the current music the playback progress, the reason uses the Seekbar without ProgressBar is because we need the music fast forward fast rewind function, may drag the slider to change the progress There is also a textview, used to display the current song name, duration and so on. At the bottom is the 4 button, which is the previous one, play (pause), stop, the next song.
We note that as far as possible in the layout appears directly in the interface of the text content, we put these content in the res/values under the Strings.xml, and then refer to them separately, so nurturance good habits, interface and content separation, convenient debugging and later maintenance. Now our interface is as follows:
Then we open the File Explorer, in Eclipse's window-show View-the other--android--file Explore. You can also alt+shift+q directly.
Under the Mnt/sdcard, we put a two or three songs, in the virtual machine temporarily does not support Chinese, import Chinese files will be an error.
Then we create a class, do our player's service class, I call Musicservice Bar, in which declare the following objects:
Java code
public class Musicservice {
private static final File Music_path = Environment
. getExternalStorageDirectory (); /Find the path where music is stored.
the public list<string> musiclist;//stores the absolute path of all MP3 found. Public
MediaPlayer player;//define Multimedia object public
int songnum;//The Subscript public
String Songname of the current playlist The song name
}
Then we're going to load the MP3 file we just added, and here's a variety of ways to write a simple one:
Java code
Class Musicfilter implements FilenameFilter {public
Boolean accept (File dir, String name) {return
(name.endsw ITH (". mp3"));//return all files with the. mp3 End of the current directory
}
}
Instantiate the object in the parameterless constructor of the Musicservice class and place the MP3 files in the musiclist.
Java code
Public Musicservice () {
musiclist = new arraylist<string> ();
Player = new MediaPlayer ();
if (Music_path.listfiles () (New Musicfilter ()). length > 0) {for
(File file:MUSIC_PATH.listFiles (new Musicfilter) )) {
Musiclist.add (File.getabsolutepath ());}}}
Let's write a method to set the name of the current song: (personally think this method is more stupid, but not think of another way)
Java code
The public void Setplayname (String dataSource) {
File File = new file (dataSource);//is assumed to be D:\\mm.mp3
String name = Fil E.getname ();//name=mm.mp3
int index = Name.lastindexof ("."); /Find the last one.
Songname = name.substring (0, index);//intercept as MM
}
The next step is the basic method of our service class, which is start, pause, stop, previous and next.
We can do this by using the start, pause, and stop methods of the declared multimedia object respectively.
Java code
public void Start () {try {player.reset ();//reset multimedia String DataSource = Musiclist.get (songnum);/Get current play Music The path Setplayname (dataSource);//Intercept song name Player.setdatasource (DataSource); Set the playback path for the Multimedia object Player.prepare (); Play Player.start ()//start playing//setoncompletionlistener event that occurs when the current multimedia object playback completes Player.setoncompletionlistener (new
Oncompletionlistener () {public void oncompletion (MediaPlayer arg0) {next ()//If the current song is finished, play the next one automatically.
}
});
catch (Exception e) {log.v ("Musicservice", E.getmessage ());
} public void Next () {songnum = Songnum = = Musiclist.size ()-1? 0:songnum + 1;
Start ();
public void Last () {songnum = Songnum = = 0 musiclist.size ()-1:songnum-1;
Start ();
public void Pause () {if (player.isplaying ()) Player.pause ();
else Player.start ();
public void Stop () {if (player.isplaying ()) {player.stop ());
}
}
So far our service class is finished, and then we go to the activity to bind the events for each control.
In this activity, the hardest thing to do is to drag the Seekbar slider to change the progress of the play, and here I think twice, with a handler class to deal with.
Handler is responsible for sending and processing messages in Android. Its main uses are:
1. Send a message or execute a runnanble (using the Post method) as scheduled.
2. Messages sent from other threads are placed in Message Queuing to avoid thread conflicts (common to updating UI threads).
By default, Handler accepts a message loop instance under the current thread (using Handler (Looper looper), Handler (Looper looper, Handler.callback Callback) to specify the thread). At the same time, a message queue can be distributed and processed by multiple objects in the current thread (in the UI thread, the system already has an activity to handle, and you can handle it again with several handler). When instantiating a handler, Looper can be any thread, and any thread can be sendmessage as long as there is a handler pointer. handler for message processing is not concurrent. A looper will read the next one only after processing one message, so the message is handled in a blocking form (the Handlemessage () method should not have time-consuming operations that can place time-consuming operations on other threads. Sends a message (via the Sendmessges method) after the operation, and then updates the UI by Handlemessage ().
Declare the following variables:
Java code
Private Button btnstart, Btnstop, Btnnext, Btnlast;
Private TextView Txtinfo;
Private ListView ListView;
Private SeekBar SeekBar;
Private Musicservice Musicservice;
Private Musichandler musichandler;//Handle Change progress bar event
Private Musicthread musicthread;//automatically change progress bar thread
Private Boolean Autochange, manulchange;//judge whether the progress bar is changed automatically or manually change the
private Boolean ispause;//determine whether to resume or replay from the pause
If you have an error, you can comment it out without having to manage it, and then bind the event in the initialization process.
This is the ListView Fill method:
Java code
private void Setlistviewadapter () {
list<map<string, object>> date = new Arraylist<map<string, Object>> ();
for (String path:musicService.musicList) {
map<string, object> Map = new hashmap<string, object> ();
file file = new file (path);
Map.put ("FileName", File.getname ());
Date.add (map);
Simpleadapter adapter = new Simpleadapter (this, date,
Android. R.layout.simple_list_item_1,
new string[] {"FileName"}, new int[] {Android. R.ID.TEXT1});
Listview.setadapter (adapter);
}
The Simpleadapter constructors are:
Public Simpleadapter (context, list<? extends Map<string,?>> data, int resource, string[] from, int[] To);
The first parameter context refers to which activity is displayed.
The second parameter is a generic as a data source, and a row in each list represents a row that is rendered, and the key of the map is the column name of the row, and the value is also named.
The third parameter is the resource file, which means that the view resource file that you need to load this column, I refer directly to the resources built into the system, if you want the beautiful style to write yourself.
The fourth argument is a string array that maps the names in the map object to the column names.
The fifth is the display of the value one by one object of the fourth parameter (one by one corresponds) in the next int ID array, this ID array is the unique int identifier formed by the named ID in the layout XML file.
Seekbar Stop the Dragged event:
Java code
public void Onstoptrackingtouch (SeekBar SeekBar) {//stop dragging
int progress = seekbar.getprogress ();
if (!autochange && manulchange) {
int musicmax = MusicService.player.getDuration ();///Get the longest number of seconds for the song
int Seekbarmax = Seekbar.getmax ();
Musicservice.player
. Seekto (Musicmax * progress/seekbarmax);//Skip to the song for the
second musicservice.pause ();
Autochange = true;
Manulchange = false;
}
}
Implementation of the Musichandler class:
Java code
Class Musichandler extends Handler {public musichandler () {} @Override the public void Handlemessage ( Message msg) {if (Autochange) {try {int position = musicService.player.getCurrentPosition ();// To the current song playback progress (sec) int mmax = MusicService.player.getDuration ();/max seconds int smax = Seekbar.getmax ();//seekbar
Max value, percent seekbar.setprogress (position * smax/mmax);
Txtinfo.settext (Setplayinfo (position/1000, mmax/1000));
catch (Exception e) {e.printstacktrace ();
} else {seekbar.setprogress (0);
Txtinfo.settext ("Play has stopped"); }//Set the information that is currently playing private string setplayinfo (int position, int max) {string info = "Playing:" + Musicservic
E.songname + "\t\t";
Stupid way to write the memory can be used%, but do not want to change the int pminutes = 0;
while (position >=) {pminutes++;
Position-= 60; } String now = (Pminutes < 10?) "0" + Pminutes:pminutes) + ":" + (Position < 10?)
0 "+ position:position);
int mminutes = 0;
while (Max >=) {mminutes++;
Max-= 60; } String all = (Mminutes < 10?) "0" + mminutes:mminutes) + ":" + (Max < 10?)
0 "+ Max:max);
Return info + now + '/' + all;
}
Implementation of Musicthread:
Java code
Class Musicthread implements Runnable {
@Override public
void Run () {while
(true)
try {
Musichandler.sendmessage (New Message ());
Thread.Sleep (1000),//1 seconds per interval send update message
} catch (Interruptedexception e) {
e.printstacktrace ();
}
}}
This project completes. I hope you can learn more from this example and accumulate more experience.
The above is about the development of Android simple player examples, thank you for your support of this site!