Android Multimedia Development Learning simple music player
Source: Internet
Author: User
<span id="Label3"></p><p><p>Our goal today is to learn how to create a simple music player that can support playback, pause, resume playback, and progress display that has been dragged.</p></p><p><p>Now that our purpose is clear, let's analyze it first:</p></p><p><p>1: can we play the music task on the activity?<br></p></p><p><p>Assuming our current music playback, we cut to other applications, the process of playing the music activity is a background process, because the background process will kill the current process due to insufficient system resources, which will cause the music to not play. So it's not possible to use Activity.</p></p><p><p>2: the task of playing music is placed in a service, that service has 2 start mode, should use that kind of service?</p></p><p><p>A: If you use StartServer to start the service, the service of the music playing method is not available.</p></p><p><p>B: If the service is started with bindservice, but the service is started by bindservice, the service will also exit when activity Exits.</p></p><p><p>3: so, We will be 2 in the service together, start the service with startserver, and then bind the service with bindservice, even if the activity exits, the service will work as Usual. You can also get the music control method in the Service.</p></p><p><p>And since the analysis is clear on how to do it. Then we'll start Moving.</p></p><p><p><br></p></p><p><p>The first step: create a simple activity, which has play, pause, resume playback, Exit button (layout file is not posted). Then start the service</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">Start the service and then need to bind the service conn = new Myserviceconn (); Intent = new Intent (this, musicservice.class); StartService (intent); Bindservice (intent, conn, bind_auto_create);</pre></pre><br>Step two: Create MediaPlayer in the OnCreate method of the service<p><p></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">@Overridepublic void OnCreate () {//service creation, We create mediaplayersuper.oncreate ();p layer = new MediaPlayer ();}</pre></pre><br>Step three: Start the music playback, start the music playback of course, there are steps:<p><p></p></p><p><p>Let's take a look at a picture of how to start the music</p></p><p><p></p></p><p><p>As you can see, starting music playback takes several steps:</p></p><p><p>1:reset (reset)</p></p><p><p>2:setdatasource (set Data Source)</p></p><p><p>3:prepare (preparation)</p></p><p><p>4:start (play)</p></p><p><p>If you are currently playing, you need to pause to call pause ()</p></p><p><p>Call if you want to play back from pause (onstart)</p></p><p><p>If you need to call (ONSTOP) to stop playback, you will need to re-prepare,start if you play back</p></p><p><p><br></p></p><p><p>How to start the music playback:<br></p></p><pre name="code" class="java"><pre name="code" class="java">How to play the service public void play () {///1: first reset Player.reset (); try {//2: set data Player.setdatasource ("sdcard/smallapple.mp3");//3. Prepare Player.prepare ();//4. start playing Player.start ();//5. start timer AddTimer ();} Catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}</pre></pre><br>Pause Method:<p><p></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">Service suspend service public void pause () {player.pause ();}</pre></pre><br>Continue Playback:<p><p></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">The service continues to play public void Continueplay () {player.start ();}</pre></pre><br>Fourth step: If you increase the progress display to the music playback, then we add a seekbar, so we can also drag<p><p></p></p><p><p>Now that you need to change the progress bar progress every second, you need to add a timer, the timer gets the current playback progress per second, and then notifies the UI to show the update</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">Add timer to update playback progress per second public void AddTimer () {if (timer = = Null) {timer = new timer (); timer.schedule (new timertask () {@ overridepublic void Run () {//gets The total time of the music int duration = Player.getduration ();//gets The current playing time of the music int currposition = Player.getcurrentposition ();//the data to be obtained, need to be passed to the UI update, we use MSG to send message msg = MainActivity.handler.obtainMessage ();// The data bundle is transmitted via the bundle: the new bundle ();d ata.putint ("duration", duration);d ata.putint ("currposition", currposition); Msg.setdata (data);//send a message to ActivityMainActivity.handler.sendMessage (msg);} 5 milliseconds after the start of the timer task, execute the Run method for the first time, once every 1000 milliseconds}, 5, 1000);}}</pre></pre><br>When the timer is played, the data is sent to the mainactivity for display:<p><p></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java"> static Handler Handler = new Handler () {public void handlemessage (android.os.Message msg) { Bundle data = msg . GetData (); Sbar.setmax (data.getint ("duration")); Sbar.setprogress (data.getint ("currposition"); }; };</pre></pre>Fifth Step: if we want to implement drag-and-drop, we can add seekbar change monitoring to Seekbar<br><pre name="code" class="java"><pre name="code" class="java">Sbar.setonseekbarchangelistener (new onseekbarchangelistener () {@Overridepublic void Onstoptrackingtouch (SeekBar SeekBar) {//TODO auto-generated method Stubminterface.seekto (seekbar.getprogress ());} @Overridepublic void Onstarttrackingtouch (SeekBar arg0) {//TODO auto-generated method stub} @Overridepublic void onprogresschanged (SeekBar arg0, int arg1, boolean arg2) {//TODO auto-generated method stub}});</pre></pre><br>Because we do not need to let the progress of the play when we swipe the finger, only play when the finger is lifted, then we only need to update the playback progress in the Onstoptrackingtouch<p><p></p></p><p><p><br></p></p><p><p>It's about over here, and Here's the detailed Code.</p></p><p><p>Code in Mainactivity:</p></p><p><p></p></p><pre name="code" class="java">public class Mainactivity extends Activity {musicinterface minterface;private static SeekBar sbar;private myserviceconn C Onn;private Intent Intent; @Override protected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); SBar = (SeekBar) Findviewbyid (r.id.seekbar1); Sbar.setonseekbarchangelistener (new onseekbarchangelistener () {@Overridepublic void Onstoptrackingtouch (SeekBar SeekBar) {//TODO auto-generated method Stubminterface.seekto (seekbar.getprogress ());} @Overridepublic void Onstarttrackingtouch (SeekBar arg0) {//TODO auto-generated method stub} @Overridepublic void onprogresschanged (SeekBar arg0, int arg1, boolean arg2) {//TODO auto-generated method stub}}); Start the service and then need to bind the service conn = new Myserviceconn (); Intent = new Intent (this, musicservice.class); StartService (intent); Bindservice (intent, conn, bind_auto_create); } static Handler Handler = new Handler () {public void handlemessage (android.os.Message msg) {Bundle data = Msg.getdata ( ); Sbar.setmax (data.getint ("duration")); Sbar.setprogress (data.getint ("currposition")); }; }; Class Myserviceconn implements serviceconnection {@Overridepublic void onserviceconnected (componentname arg0, ibinder A Rg1) {//get Service Middleman minterface = (musicinterface) arg1;} @Overridepublic void onservicedisconnected (componentname arg0) {//TODO auto-generated method Stub}}//start Playback public void start (View v) {minterface.play (); }//pause to play public void pause (View v) {minterface.pause (); }//continue to play public void Continueplay (View v) {minterface.continueplay (); }//exit public void Exit (View v) {///first unbind service Unbindservice (conn); In the Stop service StopService (intent); Finish (); }}</pre><br>Code in Musicservice:<p><p></p></p><p><p></p></p><pre name="code" class="java">public class Musicservice extends Service {MediaPlayer player;private timer timer; @Overridepublic ibinder onbind (Intent A Rg0) {//TODO auto-generated method Stubreturn new Musiccontroller ();} @Overridepublic void OnCreate () {//service creation, We create mediaplayersuper.oncreate ();p layer = new MediaPlayer ();} @Overridepublic void OnDestroy () {//destroy The service, you need to stop playback before releasing the resource Super.ondestroy ();//stop service Player.stop ();// Frees the underlying hardware to occupy the resource player.release ();p layer = null;if (timer! = Null) {//cancel timer timer.cancel (); timer = null;}} Class Musiccontroller extends Binder implements musicinterface{@Overridepublic void Play () {//TODO auto-generated method StubMusicService.this.play ();} @Overridepublic void Pause () {//TODO auto-generated method StubMusicService.this.pause ();} @Overridepublic void Continueplay () {//TODO auto-generated method StubMusicService.this.continuePlay ();} @Overridepublic void Seekto (int progress) {//TODO auto-generated method StubMusicService.this.seekTo (progress);}} How to play the service public void play () {///1: first reset Player.reset (); tRy {///2: Set data player.setdatasource ("sdcard/smallapple.mp3");//3. prepare Player.prepare ();//4. start playback player.start ();//5. Start Timer AddTimer ();} Catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Service suspend service public void pause () {player.pause ();} The service continues to play public void Continueplay () {player.start ();} Drag the service to move public void Seekto (int Progress) {player.seekto (progress);} Add timer to update playback progress per second public void AddTimer () {if (timer = = Null) {timer = new timer (); timer.schedule (new timertask () {@ overridepublic void Run () {//gets The total time of the music int duration = Player.getduration ();//gets The current playing time of the music int currposition = Player.getcurrentposition ();//the data to be obtained, need to be passed to the UI update, we use MSG to send message msg = MainActivity.handler.obtainMessage ();// The data bundle is transmitted via the bundle: the new bundle ();d ata.putint ("duration", duration);d ata.putint ("currposition", currposition); Msg.setdata (data);//send a message to ActivityMainActivity.handler.sendMessage (msg);} 5 milliseconds after the start of the timer task, execute the Run method for the first time, once every 1000 milliseconds}, 5, 1000);}}</pre><br>Code in Musicinterface:<p><p></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">Public interface Musicinterface {void play (); void pause (); void continueplay (); void Seekto (int progress);}</pre></pre>The display results are as follows:<p><p></p></p><p><p><br></p></p><p><p><br></p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>Android Multimedia Development Learning simple music player</p></p></span>
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