Tutorial on building an audio player for Android (2)

Source: Internet
Author: User
Tags add hours

6. Write ListView for PlayList
Use the List View (ListView) to display the playback list. Create an xml layout file named list_selector.xml in the drawable folder, which is used to gradient the background of the list items.
List_selector.xml <? Xmlversion = "1.0" encoding = "UTF-8"?>
<Selectorxmlns: android = "http://schemas.android.com/apk/res/android">
<! -- Selector style for listrow -->
<Item
Android: state_selected = "false"
Android: state_pressed = "false"
Android: drawable = "@ drawable/gradient_bg"/>
<Itemandroid: state_pressed = "true"
Android: drawable = "@ drawable/gradient_bg_hover"/>
<Itemandroid: state_selected = "true"
Android: state_pressed = "false"
Android: drawable = "@ drawable/gradient_bg_hover"/>
</Selector>


Create an xml layout file named playlist. xml in the drawable folder to display the List View.

Playlist. xml <? Xmlversion = "1.0" encoding = "UTF-8"?>
<LinearLayoutxmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: orientation = "vertical">
 
<ListView
Android: id = "@ android: id/list"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: divider = "#242424"
Android: dividerHeight = "1dp"
Android: listSelector = "@ drawable/list_selector"/>
 
</LinearLayout>


Create an xml layout file named playlist_item.xml in the drawable folder, which displays the title of a song for a single list item.
Playlist_item.xml <? Xmlversion = "1.0" encoding = "UTF-8"?>
<LinearLayoutxmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: orientation = "vertical"
Android: gravity = "center"
Android: background = "@ drawable/list_selector"
Android: padding = "5dp">
<TextView
Android: id = "@ + id/songTitle"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: textSize = "16dp"
Android: padding = "10dp"
Android: color = "# f3f3f3"/>
</LinearLayout>


By using the above layout, we can implement the following list view by loading data to it.


7. Write the class for reading mp3 files from SDcard
So far, we have completed the static layout of the player, and now the actual code starts. Create a new class file and name it SongsManager. java. This category will read all the files from the sdcardfile on the device and filter the files with only the suffix.
Songsmanager#packagecom. androidhive. musicplayer;
 
Importjava. io. File;
Importjava. io. FilenameFilter;
Importjava. util. ArrayList;
Importjava. util. HashMap;
 
PublicclassSongsManager {
// SDCard Path
FinalString MEDIA_PATH = new String ("/sdcard /");
PrivateArrayList <HashMap <String, String> songsList = new ArrayList <HashMap <String, String> ();
 
// Constructor
PublicSongsManager (){
 
}
 
/**
* Function to read all mp3 files from sdcard
* And store the details in ArrayList
**/
PublicArrayList <HashMap <String, String> getPlayList (){
File home = new File (MEDIA_PATH );
 
If (home. listFiles (newFileExtensionFilter (). length> 0 ){
For (File file: home. listFiles (newFileExtensionFilter ())){
HashMap <String, String> song = new HashMap <String, String> ();
Song. put ("songTitle", file. getName (). substring (0, (file. getName (). length ()-4 )));
Song. put ("songPath", file. getPath ());
 
// Adding each song to SongList
SongsList. add (song );
}
}
// Return songs list array
ReturnsongsList;
}
 
/**
* Class to filter files which are having. mp3 extension
**/
ClassFileExtensionFilterimplements FilenameFilter {
Publicbooleanaccept (File dir, String name ){
Return (name. endsWith (". mp3") | name. endsWith (". MP3 "));
}
}
}


8. Write List View for PlayList
Create an activity class for the PlayListActivity. java and PlayListActivity. java to display the song list by using the SongsManager. java class.
PlayListActivity. java packagecom. androidhive. musicplayer;
 
Importjava. util. ArrayList;
Importjava. util. HashMap;
 
Importandroid. app. ListActivity;
Importandroid. content. Intent;
Importandroid. OS. Bundle;
Importandroid. view. View;
Importandroid. widget. AdapterView;
Importandroid. widget. AdapterView. OnItemClickListener;
Importandroid. widget. ListAdapter;
Importandroid. widget. ListView;
Importandroid. widget. SimpleAdapter;
 
PublicclassPlayListActivity extends ListActivity {
// Songs list
PublicArrayList <HashMap <String, String> songsList = new ArrayList <HashMap <String, String> ();
 
@ Override
PublicvoidonCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. playlist );
 
ArrayList <HashMap <String, String> songsListData = new ArrayList <HashMap <String, String> ();
 
SongsManager plm = new SongsManager ();
// Get all songs from sdcard
This. songsList = plm. getPlayList ();
 
// Looping through playlist
For (inti = 0; I <songsList. size (); I ++ ){
// Creating new HashMap
HashMap <String, String> song = songsList. get (I );
 
// Adding HashList to ArrayList
SongsListData. add (song );
}
 
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter (this, songsListData,
R. layout. playlist_item, newString [] {"songTitle"}, new int [] {
R. id. songTitle });
 
SetListAdapter (adapter );
 
// Selecting single ListView item
ListView lv = getListView ();
// Listening to single listitem click
Lv. setOnItemClickListener (newOnItemClickListener (){
 
@ Override
PublicvoidonItemClick (AdapterView <?> Parent, View view,
Intposition, long id ){
// Getting listitem index
IntsongIndex = position;
 
// Starting new intent
Intent in = new Intent (getApplicationContext (),
AndroidBuildingMusicPlayerActivity. class );
// Sending songIndex to PlayerActivity
In. putExtra ("songIndex", songIndex );
SetResult (100, in );
// Closing PlayListView
Finish ();
}
});
}
}

9. Auxiliary Class Functions
Create a new class called Utilities. java, which is used to process the percentage of the progress of the additional job image conversion time, and vice versa. In addition, it has the function to convert the millisecond timer into a time string and display it on the player's seekbar.
Utilities. java packagecom. androidhive. musicplayer;
 
PublicclassUtilities {
 
/**
* Function to convert milliseconds time
* Timer Format
* Hours: Minutes: Seconds
**/
PublicString milliSecondsToTimer (longmilliseconds ){
String finalTimerString = "";
String secondsString = "";
 
// Convert total duration into time
Inthours = (int) (milliseconds/(1000*60*60 ));
Intminutes = (int) (milliseconds % (1000*60*60)/(1000*60 );
Intseconds = (int) (milliseconds % (1000*60*60) % (1000*60)/1000 );
// Add hours if there
If (hours> 0 ){
FinalTimerString = hours + ":";
}
 
// Prepending 0 to seconds if it is one digit
If (seconds <10 ){
SecondsString = "0" + seconds;
} Else {
SecondsString = "" + seconds ;}
 
FinalTimerString = finalTimerString + minutes + ":" + secondsString;
 
// Return timer string
ReturnfinalTimerString;
}
 
/**
* Function to get Progress percentage
* @ Param currentDuration
* @ Param totalDuration
**/
PublicintgetProgressPercentage (longcurrentDuration, long totalDuration ){
Double percentage = (double) 0;
 
LongcurrentSeconds = (int) (currentDuration/1000 );
LongtotalSeconds = (int) (totalDuration/1000 );
 
// Calculating percentage
Percentage = (double) currentSeconds)/totalSeconds) * 100;
 
// Return percentage
Returnpercentage. intValue ();
}
 
/**
* Function to change progress to timer
* @ Param progress-
* @ Param totalDuration
* Returns current duration in milliseconds
**/
PublicintprogressToTimer (intprogress, int totalDuration ){
IntcurrentDuration = 0;
TotalDuration = (int) (totalDuration/1000 );
CurrentDuration = (int) (double) progress)/100) * totalDuration );
 
// Return current duration in milliseconds
ReturncurrentDuration * 1000;
}
}
Author: wangjinyu501
 

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.