Android Play music-progress bar

Source: Internet
Author: User

Today, the study of the slag to play music with MediaPlayer to join the progress bar, the progress bar is now using the Android Seekbar, later will be followed by the UI, in the past can play music on the basis of, now join the main features are two:

1 show playback progress in real time

2 Manually adjust the playback progress

Now a new project to test the slag, later and the previous blog introduction of the sliding page to integrate, is expected to be integrated after the service is built, please look forward to ....

All right, first up:


The basic principle of using a progress bar is very easy and uses several parameters :

1 The length of the song: units of milliseconds, MediaPlayer getduration (), just to pay attention to the use of getduration () state, in this blog introduced the MediaPlayer of the various states, we can go to see.

2 The length of the progress bar: the length of the progress bar in Android should default to 100, the unit is unknown, not affected

3 Current progress: For a song, the current progress is the location of the song currently playing, in milliseconds, for the progress bar, is the proportion of the progress bar. The main is to convert these two.

Two functions:

1 because progress needs to be updated in real time, a thread is used in the system to send messages to the UI thread (every 100 milliseconds), to capture messages in the UI thread with handler, and to get the current position through the getcurrentposition of MediaPlayer. The corresponding position of Seekbar is calculated, and the Seekbar is updated in time.

2 for manually adjusting the progress of the song, by getting the adjustment to the position, through the Seekbar.onseekbarchangelistener () listening slider, when the slider adjustment position is determined, through Onstoptrackingtouch () to update the progress of the song in a timely way, Adjusts the progress of the song with MediaPlayer Seekto (in milliseconds).

Detailed code such as the following:

public class Mainactivity extends Activity {MediaPlayer MediaPlayer; SeekBar seekbar;//The path to the local song string path = "/storage/sdcard1/music/Romantic Full House. mp3";//Process progress bar update Handler Mhandler = new Handler () {@ Override public void Handlemessage (Message msg) {switch (msg.what) {case 0://update progress int position = MEDIAPLAYER.GETCU                            Rrentposition ();              int time = Mediaplayer.getduration ();                            int max = Seekbar.getmax ();              Seekbar.setprogress (Position*max/time);        Break                    Default:break;} }}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); init ();//Initialize playback Buttonbutton PlayButton = (Button) Findviewbyid (R.id.playbutton); Playbutton.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method Stubtoast.maketext (Mainactivity.this, "Time Is" +mediaplayer.getduration (), +). Show ();p Lay();}});/ /Initialize pause Buttonbutton Pausebutton = (Button) Findviewbyid (R.id.pausebutton);p Ausebutton.setonclicklistener (new    Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method Stubpause ();}); SeekBar = (SeekBar) Findviewbyid (R.id.seekbar); Seekbar.setonseekbarchangelistener (new Seekbar.onseekbarchangelistener () {@Overridepublic void Onstoptrackingtouch (SeekBar SeekBar) {//Manually adjust progress//TODO Auto-generated method Stubint dest = seekbar.getprogress (); int time = Mediaplayer.getduration (); int max = Seekbar.getmax ( ); Mediaplayer.seekto (Time*dest/max);} @Overridepublic void Onstarttrackingtouch (SeekBar arg0) {//TODO auto-generated method stub} @Overridepublic void Onprogresschanged (SeekBar arg0, int arg1, Boolean arg2) {//TODO auto-generated Method stub}});    Initialize music to play void Init () {//Enter Idlemediaplayer = new MediaPlayer (); try {//Initialize Mediaplayer.setdatasource (path);  Mediaplayer.setaudiostreamtype (Audiomanager.stream_music); Prepare loads the media resource asynchronously Mediaplayer.prepareasynC ();//Background thread sends a message to update progress bar final int milliseconds = 100;new thread () {@Overridepublic void run () {while (true) {TR                  Y {sleep (milliseconds); } catch (Interruptedexception e) {//TODO auto-generated catch block E.printsta                  Cktrace ();              } mhandler.sendemptymessage (0); }}}.start ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Test pilot put music void play () {Mediaplayer.start ();} Pause Music private void pause () {if (MediaPlayer! = null && mediaplayer.isplaying ()) {Me          Diaplayer.pause (); }}//activity stop playing music when exiting, freeing resources @overrideprotected void OnDestroy () {//Recycle resources at end of activity if (me             Diaplayer! = null && mediaplayer.isplaying ()) {mediaplayer.stop ();             Mediaplayer.release ();         MediaPlayer = null; } super.OnDestroy (); } @Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action Bar if it is P Resent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}

Android play music-progress bar

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.