Android Programming Development Music Player Instance _android

Source: Internet
Author: User

This article describes the Android programming development music player, share for everyone to refer to, specifically as follows:

The music player combines the following:

SeekBar, ListView, broadcast receivers (registered in the form of receiver), system services, MediaPlayer

Features to implement:

1. Pause/Play, Next/Previous, click on a song to play
2. Support drag progress bar fast Forward
3. List sort
4. When you come to the phone, stop playing, hang up and continue playing
5. Can play in the background

Effect Chart:

Interface:

Main.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" "Fill_parent"
  ;
    <textview android:id= "@+id/name" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" /> <seekbar android:id= "@+id/seekbar android:layout_width=" fill_parent "android:layout_height=" wrap _content "android:layout_marginbottom=" 5DP "/> <linearlayout android:layout_width=" Fill_parent "an droid:layout_height= "Wrap_content" android:layout_marginbottom= "20DP" > <button android:layout_wid Th= "40DP" android:layout_height= "40DP" android:text= "|◀" android:onclick= "Previous"/> < Button android:id= "@+id/pp" android:layout_width= "40DP" android:layout_height= "40DP" android:text= "▶" android:onclick= "pp"/> <button android:layout_width=" 40DP "android:layout_height=" 40DP "android:text=" ▶| " android:onclick= "Next"/> </LinearLayout> <listview android:id= "@+id/list" Android:la

 Yout_width= "Fill_parent" android:layout_height= "fill_parent"/> </LinearLayout>

Item.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
  "http://schemas.android.com/" Apk/res/android "
  android:layout_width=" fill_parent "
  android:layout_height=" Wrap_content "
  android: padding= "10DP"
  >
  <textview
    android:id= "@+id/mname"
    android:layout_width= "Fill_parent"
    android:layout_height= "wrap_content"
    android:textsize= "15sp"
    />
</LinearLayout>

Mainactivity:

Package Cn.test.audio;
Import Java.io.File;
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import android.app.Activity;
Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.IntentFilter;
Import Android.media.MediaPlayer;
Import Android.media.MediaPlayer.OnCompletionListener;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.os.Handler;
Import Android.telephony.PhoneStateListener;
Import Android.telephony.TelephonyManager;
Import Android.view.View;
Import Android.widget.AdapterView;
Import Android.widget.Button;
Import Android.widget.ListView;
Import Android.widget.SeekBar;
Import Android.widget.SimpleAdapter;
Import Android.widget.TextView;
Import Android.widget.AdapterView.OnItemClickListener;
Import Android.widget.SeekBar.OnSeekBarChangeListener; public class Mainactivity extends activity {private TEXTVIEW Nametextview;
  Private SeekBar SeekBar;
  Private ListView ListView;
  Private list<map<string, string>> data;
  private int current;
  Private MediaPlayer player;
  Private Handler Handler = new Handler ();
  Private Button Ppbutton;
  Private Boolean ispause;
  Private Boolean Isstarttrackingtouch;
    public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.main);
    Nametextview = (TextView) Findviewbyid (r.id.name);
    SeekBar = (SeekBar) Findviewbyid (R.id.seekbar);
    ListView = (ListView) Findviewbyid (r.id.list);
    Ppbutton = (Button) Findviewbyid (R.ID.PP);
    Create a music player player = new MediaPlayer ();
    Display Music playlist Generatelistview ();
    Progress bar Listener Seekbar.setonseekbarchangelistener (new Myseekbarlistener ());
    Player Listener Player.setoncompletionlistener (new Myplayerlistener ());
    Intent Filter Intentfilter filter = new Intentfilter (); Broadcast phone suspend music playback filter.addaction ("Android.intent.aCtion.
    New_outgoing_call ");
    Registerreceiver (New Phonelistener (), filter);
    Create a telephony service Telephonymanager manager = (Telephonymanager) getsystemservice (Telephony_service);
  Monitor phone status and stop playing Manager.listen (new Myphonestatelistener (), phonestatelistener.listen_call_state) when answering the phone; * * * Monitor phone status/private final class Myphonestatelistener extends Phonestatelistener {public void Oncallsta
    techanged (int state, String incomingnumber) {pause (); } * * Player listener/Private final class Myplayerlistener implements Oncompletionlistener {//Song play the next song automatically after playing
    Curved public void Oncompletion (MediaPlayer MP) {next ();
  }/* * Next button */public void Next (view view) {next);
  * * * The previous button/* public void Previous (view view) {previous ();
    * * * Play the previous song/private void Previous () {current = Current-1 < 0 data.size ()-1:current-1;
  Play ();
* * * Play next song/private void Next () {    Current = (current + 1)% data.size ();
  Play (); * * * progress bar Listener/Private Final class Myseekbarlistener implements Onseekbarchangelistener {//Mobile trigger Publi c void Onprogresschanged (SeekBar SeekBar, int progress, Boolean fromuser) {}//start triggering public void Onstarttracki
    Ngtouch (SeekBar SeekBar) {Isstarttrackingtouch = true;
      //End Trigger public void Onstoptrackingtouch (SeekBar SeekBar) {Player.seekto (seekbar.getprogress ());
    Isstarttrackingtouch = false; }/* * Display Music playlist */private void Generatelistview () {list<file> list = new arraylist<file> ()
    ;
    Gets all the songs in the SDcard FindAll (environment.getexternalstoragedirectory (), list);
    Playlists are sorted, character order Collections.sort (list);
    data = new arraylist<map<string, string>> ();
      for (File file:list) {map<string, string> Map = new hashmap<string, string> ();
      Map.put ("Name", File.getname ()); Map.put ("path"),File.getabsolutepath ());
    Data.add (map);  } simpleadapter adapter = new Simpleadapter (this, data, R.layout.item, new string[] {"Name"}, new int[] {R.id.mname
    });
    Listview.setadapter (adapter);
  Listview.setonitemclicklistener (New Myitemlistener ()); Private Final class Myitemlistener implements Onitemclicklistener {public void Onitemclick (Adapterview<?> p
      Arent, view view, int position, long id) {current = position;
    Play ();
      } private void Play () {try {//Replay player.reset ();
      Gets the song path Player.setdatasource (current). Data.get ("path");
      Buffer Player.prepare ();
      Start playing Player.start ();
      Displays the song name Nametextview.settext (current). Data.get ("name");
      Set the progress bar length Seekbar.setmax (player.getduration ());
      Play button style Ppbutton.settext ("| |"); Send a Runnable and handler will execute the run () method Handler.post (new Runnable () {public void run () {//update) after it is receivedDegree bar status if (!isstarttrackingtouch) seekbar.setprogress (Player.getcurrentposition ());
        Send handler.postdelayed again after 1 seconds (this, 1000);
    }
      });
    catch (Exception e) {e.printstacktrace ();  }/** * Find all MP3 files in the file path * @param file the directory you are looking for * @param list for file list/private void FindAll (file file,
    List<file> list) {file[] subfiles = File.listfiles (); if (subfiles!= null) for (File subfile:subfiles) {if (Subfile.isfile () && subfile.getname (). Ends
        With (". mp3")) List.add (subfile); else if (subfile.isdirectory ())//If is the directory FindAll (subfile, list); Recursive}/* * Pause/play button/public void pp (view view) {//default from first song to play if (!player.isplaying)
      ;&!ispause) {play ();
    Return
    Button button = (button) view; Pause/Play button if ("| |").
      Equals (Button.gettext ())) {pause ();
    Button.settext ("▶"); } ELSE {resume ();
    Button.settext ("| |");
      /* * Start operation/private void resume () {if (ispause) {Player.start ();
    Ispause = false; }/* * Suspend operation/private void pause () {if (player!= null && player.isplaying ()) {PLAYER.P
      Ause ();
    Ispause = true; } * * * When the broadcast is received/* Private Final class Phonelistener extends Broadcastreceiver {public void OnReceive (Co
    ntext context, Intent Intent) {pause ();
    }/* * Resume Playback * @see Android.app.activity#onresume ()/protected void Onresume () {super.onresume ();
  Resume ();

 }
}

Registration permissions:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android=
"http://schemas.android.com/apk/res/" Android "
   package=" Cn.itcast.audio "
   android:versioncode=" 1 "
   android:versionname=" 1.0 ">
  < Application android:icon= "@drawable/icon" android:label= "@string/app_name" > <activity android:name=
    ". Mainactivity "
         android:label=" @string/app_name ">
      <intent-filter>
        <action android:name=" Android.intent.action.MAIN "/>
        <category android:name=" Android.intent.category.LAUNCHER "/>"
      </intent-filter>
    </activity>
  </application>
  <uses-sdk android:minsdkversion = "8"/>
  <!--monitor phone calls-->
  <uses-permission android:name= "android.permission.PROCESS_OUTGOING_ CALLS "/>
  <!--monitor phone status change-->
  <uses-permission android:name=" android.permission.READ_PHONE_ State "/>
</manifest>

I hope this article will help you with your Android programming.

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.