Android Developer's simple music player

Source: Internet
Author: User

Recently started learning audio related. So, I really want to do a music player, so, spent a day to learn, the player's basic skills can be realized. I think the learning point is still quite a lot of, so write a blog summary about a music player implementation of the logic. I hope this blog post is helpful to your study and life. :

* * Implement Logic * *

On the market Music play app, instantly you turn off. So the same will play in the background, so the logic of the play should be written in the service. and the ability to communicate between service and activity. Then service is one of the four components, so be sure not to forget to declare it in the configuration file when you use it.

     <service android:name= "Com.yakir.services.MusicService" >        </service>

We need to rewrite three methods in the service, OnCreate (),Onstartcommand (),OnDestroy ().

OnCreate (): This method is called when the service starts for the first time and can be initialized with some variables.

Onstartcommand (): The service calls this method every time it is started, and can write some business logic in this method.

OnDestroy (): Called when service is destroyed to release resources.

Next, if you need to play a music file, you can encapsulate the playback logic by using the player MediaPlayerthat comes with Android:

    //Start     Public voidStart (String path) {Try{mediaplayer.reset ();            Mediaplayer.setdatasource (path);            Mediaplayer.prepare ();            Mediaplayer.start (); Mediautils.currentstate=Constants.play_start; } Catch(IOException e) {e.printstacktrace (); }    }    //Pause     Public voidpause () {if(mediaplayer!=NULL&&mediaplayer.isplaying ())            {Mediaplayer.pause (); Mediautils.currentstate=Constants.play_pause; }    }    //continue playing     Public voidContinueplay () {if(mediaplayer!=NULL&&!mediaplayer.isplaying ())            {Mediaplayer.start (); Mediautils.currentstate=Constants.play_start; }    }    //Stop playing     Public voidStop () {if(mediaplayer!=NULL) {mediaplayer.stop (); Mediautils.currentstate=Constants.play_stop; }    }

We know that the UI is written in the activity, then it involves communication between activity and service, there are 5 ways of communication between them, here I use intent, call StartService () to communicate,

At the same time, let intent carry a set of key-value pairs of data to match the service side.

Activity:

   private void Startmusicservice (String option,string path) {Intent Intentservice = new Intent (Mainactivity.this,        Musicservice.class);        Intentservice.putextra ("option", option);        Intentservice.putextra ("Messenger", new Messenger (handler));        Intentservice.putextra ("path", path);    StartService (Intentservice); } private void Startmusicservice (String option) {Intent intentservice = new Intent (Mainactivity.this, Musicserv        Ice.class);        Intentservice.putextra ("option", option);        Intentservice.putextra ("Messenger", new Messenger (handler));    StartService (Intentservice); } private void Startmusicservice (String option,int progress) {Intent intentservice = new Intent (mainactivity.th        is, Musicservice.class);        Intentservice.putextra ("option", option);        Intentservice.putextra ("Progress", progress);        Intentservice.putextra ("Messenger", new Messenger (handler));    StartService (Intentservice); }

Service:

@Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {LOG.E ("Thread", Thread.CurrentThread (). GetName ()); String option=intent.getstringextra ("option"); if(messenger==NULL) {Messenger= (Messenger) Intent.getextras (). Get ("Messenger")); }        if("Start". Equals (option)) {Start (Intent.getstringextra ("Path")); } Else if("Pause". Equals (option))        {Pause (); } Else if("Continue". Equals (option))        {Continueplay (); } Else if("Stop". Equals (option))        {Stop (); } Else if("Jump". Equals (option)) {Seekplay (Intent.getintextra ("Progress",-1)); }        return Super. Onstartcommand (Intent, flags, Startid); }

In this way, the communication between the two is achieved, and then, when I click on the next song, the next item is highlighted and the next song is played.

Get all the audio data from the system first:

    Public Static voidgetsonglist (Context context) {musicbeanlist.clear (); Uri URI=MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Cursor Cursor=context.getcontentresolver (). Query (URI,Newstring[]{MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.DATA},NULL,NULL,NULL);  while(Cursor.movetonext ()) {Musicbeanlist.add (NewMusicbean (cursor.getstring (Cursor.getcolumnindex (MediaStore.Audio.Media.TITLE)), Cursor.getstring (Cursor.getcolumnindex (MediaStore.Audio.Media.ARTIST)), cursor.getstring (cursor.getc        Olumnindex (MediaStore.Audio.Media.DATA))); }    }

Through the content provider, get all the audio data of the system, as well as the relevant information of the audio. Data is the audio path, and the audio path can be played back to the actual location of the switch. (It's very simple here, not in detail)

Working with text highlighting:

We need to know the current item position and the next item position, when the next song is clicked, the next position is highlighted and the other location is not lit. So, we need to define a constant record of the current position, and when you click on the next one, the constant increases, the previous one, and the constant decreases.

    CaseR.id.ib_bottom_last:setcolor (Color.Blue); Mediautils.currentposition--;                  SetColor (color.red); Startmusicservice (Start, MediaUtils.musicBeanList.get (mediautils.currentposition). path);              Imgbottomplay.setimageresource (R.drawable.appwidget_pause);  Break;  CaseR.id.ib_bottom_next:setcolor (Color.Blue); Mediautils.currentposition++;                  SetColor (color.red); Startmusicservice (Start, MediaUtils.musicBeanList.get (mediautils.currentposition). path);              Imgbottomplay.setimageresource (R.drawable.appwidget_pause);  Break;

You need to do a bit of logic when changing colors:

When the last item is clicked, the next highlight becomes the first one, and when the first one, click on the previous one and highlight at the last position.

 private  void  setcolor (int   color) { if  (Mediautils.curr Entposition==mediautils.musicbeanlist.size ()) {mediautils.currentposition         =0 if  (Mediautils.currentposition==-1 =mediautils.musicbeanlist.size () -1; } TextView TextView  = (TextView) Songlist.findviewwithtag (mediautils.currentpo        Sition);  if  (Textview!=null  ) {Textview.settextcolor (color); }    }

Next, you need to implement a progress bar with music playback, which requires the service to the activity of communication, through the message mechanism, let the service send messages to the activity, the playback information to the activity.

Take this intent and pass a messenger (Messager).

Intentservice.putextra ("Messenger",new Messenger (handler));

thereby the service:

                                Message message=message.obtain ();                                Message.arg1=currentpostion;                                MESSAGE.ARG2=duration;                                Message.what=constants.music_prepare;                                Messenger.send (message);

Activity re-processing:

    PrivateHandler handler=NewHandler () {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { CaseConstants.music_prepare:intcurduration=Msg.arg1; inttotalduration=msg.arg2;                    Tv_curduration.settext (Mediautils.duration2str (curduration));                    Tv_totalduration.settext (Mediautils.duration2str (totalduration));                    Sk_duration.setmax (totalduration);                    Sk_duration.setprogress (curduration);  Break; }        }    };

Set the listener in Seekbar, pass the current progress to the service when the drag is stopped, and let the music play on the current position:

Sk_duration.setonseekbarchangelistener (NewSeekbar.onseekbarchangelistener () {@Override Public voidOnprogresschanged (SeekBar SeekBar,intProgressBooleanFromuser) {} @Override Public voidOnstarttrackingtouch (SeekBar SeekBar) {} @Override Public voidOnstoptrackingtouch (SeekBar SeekBar) {sk_duration.setprogress (seekbar.getprogress ()); Startmusicservice (Jump, Seekbar.getprogress ()); }        });

At the same time, we need to note that when the phone is started, the music should be stopped, the audio focus can be obtained through Audiomanager, and the music should stop when the focus is lost:

Audiomanager audiomanager=(Audiomanager) Getsystemservice (Context.audio_service); Audiomanager.requestaudiofocus (NewAudiomanager.onaudiofocuschangelistener () {@Override Public voidOnaudiofocuschange (intFocuschange) {                Switch(focuschange) { CaseAudioManager.AUDIOFOCUS_GAIN:mediaPlayer.start (); Mediaplayer.setvolume (1.f,2.0f);  Break;  CaseAudiomanager.audiofocus_loss:if(Mediaplayer.isplaying ()) mediaplayer.stop ();                            Mediaplayer.release (); MediaPlayer=NULL;  Break;  Caseaudiomanager.audiofocus_gain_transient:if(Mediaplayer.isplaying ());                        Mediaplayer.pause ();  Break; }}},audiomanager.stream_music,audiomanager.audiofocus_gain);

OK, so a simple music player is finished, although the code is not very difficult, but there are a lot of knowledge points, such as the service in the activity of communication, and the ListView related, as well as the logic of the program, so I have a few important points summed up a bit. Hope this blog post on your life and learning to help, if there is any doubt can leave a message below, if you want the source, you can talk about me ~

Android Developer's simple music player

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.