Implement the music player step by step

Source: Internet
Author: User

Before the Chinese New Year's Eve, I have already worked on an android music player that imitates the music player project. The basic function of this player has been implemented, but the biggest problem is that the playback code is processed in the activity, when the music playing interface is launched, the music needs to be played again. When the phone is sent, the music needs to be paused and played again after the phone is called. Therefore, the previous version is still very problematic, today, we decided to implement a fully functional player step by step and put the playback control code in the service.

First, we will implement such a simple interface:

Create an android project ,:

Copy the images used in the project to the drawable directory and write main. xml

<?xml version="1.0" encoding="utf-8"?><TabHost xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@android:id/tabhost"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:orientation="vertical"        android:padding="5dp" >        <TabWidget            android:id="@android:id/tabs"            android:layout_width="fill_parent"            android:layout_height="wrap_content" />        <FrameLayout            android:id="@android:id/tabcontent"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:padding="5dp" />    </LinearLayout></TabHost>

Compile mainactivity class

Public class mainactivity extends tabactivity {/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); requestwindowfeature (window. feature_no_title); this. getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen); setcontentview (R. layout. main); resources res = getresources (); tabhost = gettabhost (); tabhost. tabspec; intent = new intent (). setclass (this, listactivity. class); spec = tabhost. newtabspec ("Music "). setindicator ("Music", Res. getdrawable (R. drawable. ITEM )). setcontent (intent); tabhost. addtab (SPEC); intent = new intent (). setclass (this, artistsactivity. class); spec = tabhost. newtabspec ("artist "). setindicator ("artist", Res. getdrawable (R. drawable. artist )). setcontent (intent); tabhost. addtab (SPEC); intent = new intent (). setclass (this, albumsactivity. class); spec = tabhost. newtabspec ("album "). setindicator ("album", Res. getdrawable (R. drawable. album )). setcontent (intent); tabhost. addtab (SPEC); intent = new intent (). setclass (this, songsactivity. class); spec = tabhost. newtabspec ("recently played "). setindicator ("Recent playback", Res. getdrawable (R. drawable. album )). setcontent (intent); tabhost. addtab (SPEC); tabhost. setcurrenttab (0 );}}

Note that tabactivity should be inherited here. We will not describe the usage of tabhost too much on the official website. Create other activities and XML layout files respectively. Do not forget to register them in manifest,

In this way, the above main interface is complete.

Next, let's take a look at how to traverse the music file and display it on the interface through listview,

Create a musiclist class in the corresponding directory. This is a common class. To load music files

Public class musiclist {public static list <music> getmusicdata (context) {list <music> musiclist = new arraylist <music> (); contentresolver Cr = context. getcontentresolver (); If (CR! = NULL) {// obtain all songs. cursor = CR. query (mediastore. audio. media. external_content_uri, null, mediastore. audio. media. default_sort_order); If (null = cursor) {return NULL;} If (cursor. movetofirst () {do {Music M = new music (); String title = cursor. getstring (cursor. getcolumnindex (mediastore. audio. media. title); string singer = cursor. getstring (cursor. getcolumnindex (mediastore. audio. media. artist); If ("<Unknown> ". equals (singer) {singer = "unknown artist";} string album = cursor. getstring (cursor. getcolumnindex (mediastore. audio. media. album); long size = cursor. getlong (cursor. getcolumnindex (mediastore. audio. media. size); long time = cursor. getlong (cursor. getcolumnindex (mediastore. audio. media. duration); string url = cursor. getstring (cursor. getcolumnindex (mediastore. audio. media. data); string name = cursor. getstring (cursor. getcolumnindex (mediastore. audio. media. display_name); M. settitle (title); M. setsinger (singer); M. setalbum (album); M. setsize (size); M. settime (time); M. seturl (URL); M. setname (name); musiclist. add (m);} while (cursor. movetonext () ;}} return musiclist ;}}

Here is the music information obtained through contentresolver, because the system provides contentprovder to facilitate the sharing of music information between applications, so I did not traverse the music files under the SD card.
Music class:

public class Music  {  private String title;private String singer;private String album;private String url;private long size;private long time;private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getSinger() {return singer;}public void setSinger(String singer) {this.singer = singer;}public String getAlbum() {return album;}public void setAlbum(String album) {this.album = album;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public long getSize() {return size;}public void setSize(long size) {this.size = size;}public long getTime() {return time;}public void setTime(long time) {this.time = time;}}

To use a custom adapter, create an XML file that matches the adapter in layout.

<? 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: layout_margintop = "2dip" Android: Background = "#00000000" Android: orientation = "horizontal"> <imageview Android: Id = "@ + ID/music_item_image" Android: layout_width = "40dp" Android: layout_height = "40dp" Android: layout_gravity = "center" Android: Background = "@ drawable/item" Android: paddingright = "10dip"/> <linearlayout Android: layout_width = "fill_parent" Android: layout_height = "60dip" Android: layout_weight = "1" Android: layout_marginleft = "3dp" Android: gravity = "center_vertical" Android: Orientation = "vertical"> <textview Android: id = "@ + ID/music_item_name" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: layout_gravity = "center_vertical" Android: textcolor = "# ffffff" Android: textsize = "18dp" Android: text = "still love you" Android: textstyle = "bold"/> <textview Android: Id = "@ + ID/music_item_singer" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: layout_gravity = "center_vertical" Android: layout_margintop = "5dip" Android: textcolor = "# ffffff" Android: TEXT = "Wang Lihong" Android: textsize = "12dp"/> </linearlayout> <textview Android: Id = "@ + ID/music_item_time" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_gravity = "center" Android: paddingright = "5dip" Android: text = "0:42" Android: textcolor = "# ffffff"/> </linearlayout>

Next is the custom adapter musicadapter.

Public class musicadapter extends baseadapter {private list <music> listmusic; private context; Public musicadapter (context, list <music> listmusic) {This. context = context; this. listmusic = listmusic;} public void setlistitem (list <music> listmusic) {This. listmusic = listmusic;} @ overridepublic int getcount () {// todo auto-generated method stubreturn listmusic. size () ;}@ overridepublic object getitem (INT arg0) {// todo auto-generated method stubreturn listmusic. get (arg0) ;}@ overridepublic long getitemid (INT position) {// todo auto-generated method stubreturn position ;}@ overridepublic view getview (INT position, view convertview, viewgroup parent) {// todo auto-generated method stubif (convertview = NULL) {convertview = layoutinflater. from (context ). inflate (R. layout. music_item, null);} music m = listmusic. get (position); // The music name textview textmusicname = (textview) convertview. findviewbyid (R. id. music_item_name); textmusicname. settext (M. getname (); // artist textview textmusicsinger = (textview) convertview. findviewbyid (R. id. music_item_singer); textmusicsinger. settext (M. getsinger (); // duration textview textmusictime = (textview) convertview. findviewbyid (R. id. music_item_time); textmusictime. settext (totime (INT) M. gettime (); Return convertview;}/*** time format conversion * @ Param time * @ return */Public String totime (INT time) {time/= 1000; int minute = Time/60; int hour = minute/60; int second = time % 60; minute % = 60; return string. format ("% 02d: % 02d", minute, second );}}

I found the time format conversion on the Internet and called the totime method to get the formatted time.

Add an adapter in listactivity:

public class ListActivity extends Activity {private ListView listView;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.listmusic);listView= (ListView) this.findViewById(R.id.listAllMusic);List<Music> listMusic=MusicList.getMusicData(getApplicationContext());MusicAdapter adapter=new MusicAdapter(this, listMusic);listView.setAdapter(adapter);}}

In this way, the music file will be loaded. Let's see the effect:

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.