Mediaplayer + service MP3 player for Android Development

Source: Internet
Author: User
Import Java. io. file; import Java. io. filenamefilter; import Java. util. arraylist; import Java. util. list; import android. app. listactivity; import android. apps. service. playerservice; import android. content. intent; import android. media. audiomanager; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. arrayadapter; import android. widget. button; import Droid. widget. seekbar; import android. widget. toast; public class testmediaplayer extends listactivity {/* some time ago, when I first learned Android, I thought mediaplayer was amazing and I tried to make a simple music player. * Supports background playback, drag-and-drop of progress bars, volume control, and reading sdcard music files for playback. **/Private button playbutton = NULL; private button mfrontbutton = NULL; private button mlastbutton = NULL; private button exit = NULL;/* volume manager */private audiomanager maudiomanager = NULL; /* define the progress bar */public static seekbar audioseekbar = NULL;/* define the volume size */private seekbar audiovolume = NULL;/* set it to a data playback list, used to store the files searched from the specified file */public static list <string> mmusiclist = new arraylist <string> ();/* defines the music storage path *// /Private Static final string music_path = new string ("/mnt/sdcard/"); // Android 2.2 Private Static final string music_path = new string ("/sdcard /"); // Android 2.1/* defines the current selection item in the playlist */public static int currentlistitme = 0; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main);/* update list */musiclist ();/* Get control */playbutton = (button) findv Iewbyid (R. id. startmusic); mfrontbutton = (button) findviewbyid (R. id. frontbutton); mlastbutton = (button) findviewbyid (R. id. lastmusic); audiovolume = (seekbar) findviewbyid (R. id. audiovolume); exit = (button) findviewbyid (R. id. exit); audioseekbar = (seekbar) findviewbyid (R. id. seekbar01);/* Play, pause listener */playbutton. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {playmusic (appcon Stant. playermag. pause) ;}});/* Listen to the next line */mfrontbutton. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {nextmusic () ;}});/* Listen to the previous line */mlastbutton. setonclicklistener (new view. onclicklistener () {@ overridepublic void onclick (view v) {frontmusic () ;}});/* Quit listening */exit. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {intent = new intent (); Intent. Setclass (testmediaplayer. this, playerservice. class); stopservice (intent); // stop servicetry {testmediaplayer. this. finish (); // close the current activity} catch (throwable e) {e. printstacktrace () ;}});/* playback progress listener */audioseekbar. setonseekbarchangelistener (New seekbarchangeevent ();/* keep the progress bar updated continuously when you enter the program again after exiting */If (playerservice. mmediaplayer! = NULL) {// sets the maximum value of the progress bar testmediaplayer. audioseekbar. setmax (playerservice. mmediaplayer. getduration (); audioseekbar. setprogress (playerservice. mmediaplayer. getcurrentposition ();}/* Get the current volume object */maudiomanager = (audiomanager) getsystemservice (audio_service);/* assign the current volume value to the progress bar */audiovolume. setprogress (maudiomanager. getstreamvolume (audiomanager. stream_music);/* Listen to the volume */audiovolume. setonseekbarchangelistener (New audiovolumechangeevent ();} public void playmusic (INT action) {intent = new intent (); intent. putextra ("MSG", action); intent. setclass (testmediaplayer. this, playerservice. class);/* start the service in androidmanifest. XML registration example: <service> </service> */startservice (intent);}/* Check the sdcard MP3 file and add it to the list */Public void musiclist () {// clear the cached mmusiclist in the list first. clear ();/* read the file from the specified path and associate it with the playlist */file home = new file (music_path); system. out. println (home. canread ();/* read a file of the specified type. In this program, set the playback type to MP3 */If (home. listfiles (New musicfilter ()). length> 0) {/* Read File */For (File file: Home. listfiles (New musicfilter () {mmusiclist. add (file. getname ();}/* Association Between the playback file and the playback list */arrayadapter <string> musiclist = new arrayadapter <string> (testmediaplayer. this, R. layout. musictime, mmusiclist); setlistadapter (musiclist) ;}}/* volume listener */class audiovolumechangeevent implements seekbar. onseekbarchangelistener {@ overridepublic void onprogresschanged (seekbar, int progress, Boolean fromuser) {// maudiomanager. adjustvolume (audiomanager. adjust_lower, 0); maudiomanager. setstreamvolume (audiomanager. stream_music, progress, 0) ;}@ overridepublic void onstarttrackingtouch (seekbar) {}@ overridepublic void onstoptrackingtouch (seekbar) {}}/* music selection listener */@ overrideprotected void onlistitemclick (Android. widget. listview L, view V, int position, long ID) {super. onlistitemclick (L, V, position, ID); currentlistitme = position; playmusic (appconstant. playermag. play_mag);}/* play the next one */private void nextmusic () {If (++ currentlistitme> = mmusiclist. size () {toast. maketext (testmediaplayer. this, "has reached the last song", toast. length_short ). show (); currentlistitme = mmusiclist. size ()-1;} else {playmusic (appconstant. playermag. play_mag) ;}}/* play the previous song */private void frontmusic () {If (-- currentlistitme> = 0) {playmusic (appconstant. playermag. play_mag);} else {toast. maketext (testmediaplayer. this, "has reached the first song", toast. length_short ). show (); currentlistitme = 0 ;}}/* playback file selection class */class musicfilter implements filenamefilter {public Boolean accept (File Dir, string name) {/* specify the extension type. You can add another music format */Return (name. endswith (". MP3 ");}/* drag and drop progress listener. Do not forget to refresh the progress bar in the Service */class seekbarchangeevent implements seekbar. onseekbarchangelistener {@ overridepublic void onprogresschanged (seekbar, int progress, Boolean fromuser) {/* assume that the change is caused by user dragging */If (fromuser) {playerservice. mmediaplayer. seekto (Progress); // when the progress bar value changes, the music player starts playing from the new position }}@ overridepublic void onstarttrackingtouch (seekbar) {playerservice. mmediaplayer. pause (); // when you start dragging the progress bar, the music is paused.} @ overridepublic void onstoptrackingtouch (seekbar) {playerservice. mmediaplayer. start (); // the music starts playing when the progress bar is stopped }}

Service

First, we recommend that you do not put the playing music in the activity, because after the activity is disabled, the background cannot be played. Therefore, to play music in the service, we only need to manage the communication between the activity and the service. The following is a service class. Directly view comments and code:

Package android. apps. service; import Java. io. ioexception; import android. app. service; import android. content. intent; import android. media. mediaplayer; import android.net. uri; import android. OS. ibinder; import android. widget. toast; import android. apps. *; public class playerservice extends Service implements runnable, mediaplayer. oncompletionlistener {/* specifies a multimedia object */public static mediaplayer mmediaplayer = NUL L; // whether the single loop is Private Static Boolean isloop = false; // The user operates private int MSG; /* define the path of the folder to be played */Private Static final string music_path = new string ("/sdcard/"); @ overridepublic ibinder onbind (intent) {return NULL; // The binding here is not used. In the previous article, I posted the code for binding activity and service} @ overridepublic void oncreate () {super. oncreate (); If (mmediaplayer! = NULL) {mmediaplayer. reset (); mmediaplayer. release (); mmediaplayer = NULL;} mmediaplayer = new mediaplayer ();/* monitor whether playback is complete */mmediaplayer. setoncompletionlistener (this) ;}@ overridepublic void ondestroy () {super. ondestroy (); If (mmediaplayer! = NULL) {mmediaplayer. stop (); mmediaplayer. release (); mmediaplayer = NULL;} system. out. println ("service ondestroy");}/* method used to start the service */@ overridepublic int onstartcommand (intent, int flags, int startid) {/* get the action sent from startservice, followed by the default parameter. Here is my custom constant */MSG = intent. getintextra ("MSG", appconstant. playermag. play_mag); If (MSG = appconstant. playermag. play_mag) {playmusic ();} If (MSG = appconstant. player Mag. pause) {If (mmediaplayer. isplaying () {// playing the mmediaplayer. pause (); // pause} else {// No mmediaplayer is played. start () ;}} return Super. onstartcommand (intent, flags, startid) ;}@ suppresswarnings ("static-access") Public void playmusic () {try {/* reset multimedia */mmediaplayer. reset ();/* read MP3 file */mmediaplayer. setdatasource (music_path + testmediaplayer. mmusiclist. get (testmediaplayer. currentlistitme); // URI uri = Uri. parse (Music_path + testmediaplayer. mmusiclist. get (testmediaplayer. currentlistitme); // mmediaplayer. create (playerservice. this, Uri);/* prepare to play */mmediaplayer. prepare ();/* start playing */mmediaplayer. start ();/* single loop */mmediaplayer. setlooping (isloop); // sets the maximum value of the progress bar testmediaplayer. audioseekbar. setmax (playerservice. mmediaplayer. getduration (); new thread (this ). start () ;}catch (ioexception e) {}// refresh progress bar @ overridepublic Vo Id run () {int currentposition = 0; // sets the current position of the default progress bar, int Total = mmediaplayer. getduration (); // while (mmediaplayer! = NULL & currentposition <total) {try {thread. Sleep (1000); If (mmediaplayer! = NULL) {currentposition = mmediaplayer. getcurrentposition () ;}} catch (interruptedexception e) {e. printstacktrace ();} testmediaplayer. audioseekbar. setprogress (currentposition) ;}}@ overridepublic void oncompletion (mediaplayer MP) {/* after the current song is played, the next song */If (++ testmediaplayer. currentlistitme> = testmediaplayer. mmusiclist. size () {toast. maketext (playerservice. this, "has reached the last song", toast. length_short ). show (); testmediaplayer. currentlistitme --; testmediaplayer. audioseekbar. setmax (0) ;}else {playmusic ();}}}

Parameter Encapsulation

/*** @ Encapsulate parameters in this way to facilitate management and reading **/public interface appconstant {public class playermag {public static final int play_mag = 1; // start playing public static final int pause = 2; // pause playing }}

Download Code: http://download.csdn.net/source/3318587

Related Article

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.