Srikanth Technologies

Audio Player in Android

This is an Android application that allows user to search for songs in MUSIC folder of SDCARD. When matching songs are listed, user can select song to play it with default music player in the device.

This application uses the following features of Android.

Steps

Here are the steps and code related to this application.
  1. First create a new Android project that supports API 10 or above. I named it as AudioPlayer
  2. Create Song class that represents a song

    src/com.st.audioplayer/Song.java

    package com.st.audioplayer;
    public class Song  {
         private String title;
         private String duration;
         private String singer;
         private String filename;
         
    	public String getFilename() {
    		return filename;
    	}
    	public void setFilename(String filename) {
    		this.filename = filename;
    	}
    	public String getTitle() {
    		return title;
    	}
    	public void setTitle(String title) {
    		this.title = title;
    	}
    	public String getDuration() {
    		return duration;
    	}
    	public void setDuration(String duration) {
    		this.duration = duration;
    	}
    	public String getSinger() {
    		return singer;
    	}
    	public void setSinger(String singer) {
    		this.singer = singer;
    	}
    }
    
  3. Create layout that represents a song

    res/layout/song.xml

    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    	android:layout_width="match_parent" android:layout_height="match_parent"
    	android:orientation="vertical">
    	
    	<TextView android:id="@+id/textTitle" android:layout_width="wrap_content" android:textColor="#0000ff"
    	    android:textAppearance="?android:attr/textAppearanceMedium"
    		android:layout_height="wrap_content" android:text="TextView" />
    
    
    	<TextView android:id="@+id/textSinger" android:layout_width="wrap_content"
    		android:layout_height="wrap_content" android:text="" />
    
    	<TextView android:id="@+id/textDuration" android:layout_width="wrap_content"
    		android:layout_height="wrap_content" android:text="" />
    
    </LinearLayout>
    
    
  4. Create layout for AudioPlayer activity

    res/layout/audioplayer.xml

    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        
       <LinearLayout  android:layout_width="match_parent"
        android:layout_height="wrap_content"  android:orientation="horizontal">
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Song Title :" />
    
        <EditText
            android:id="@+id/editTitle"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:layout_height="wrap_content">
            <requestFocus />
        </EditText>
    
        <Button
            android:id="@+id/btnSearch"
            android:onClick="searchSongs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Search" >
        </Button>
        
       </LinearLayout>
     
       <LinearLayout  android:layout_width="match_parent" android:id="@+id/songsView"
           android:layout_height="match_parent"  android:orientation="vertical">
       <TextView
           android:id="@+id/textView2"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center"
           android:text="List Of Songs"
           android:textColor="#ff0000"
           android:textStyle="bold"
           android:textSize="20sp" />
       
        <ListView
            android:id="@+id/listSongs"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="match_parent" >
        </ListView>
       </LinearLayout>
    </LinearLayout>
    
    
  5. Create code for AudioPlayer activity

    src/com.st.audioplayer/AudioPlayer.java

    package com.st.audioplayer;
    
    import java.io.File;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.media.MediaMetadataRetriever;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    
    public class AudioPlayer extends Activity {
    	ListView listSongs;
    	ArrayList<Song> songs;
    	EditText editTitle;
    	File musicFolder;
    	LinearLayout songsView;
    
    	@Override
    	protected void onRestoreInstanceState(Bundle savedInstanceState) {
    		super.onRestoreInstanceState(savedInstanceState);
    		// search for songs on restore
    		searchSongs(null);  
    	}
    
    	@Override
    	public void onCreate(Bundle state) {
    		super.onCreate(state);
    		setContentView(R.layout.audioplayer);
    		
    		// get the list of files and place them in ListView
    		listSongs = (ListView) this.findViewById(R.id.listSongs);
    		editTitle = (EditText) this.findViewById(R.id.editTitle);
    		songsView = (LinearLayout) this.findViewById(R.id.songsView);
    		songsView.setVisibility(View.INVISIBLE);
    		
    		musicFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
    		listSongs.setOnItemClickListener(new OnItemClickListener() {
    			@Override
    			public void onItemClick(AdapterView<?> view, View item,
    					int position, long id) {
    				
    				// Play song using  built-in audio player 
    				String filename = songs.get(position).getFilename();
    				Uri audio = Uri.parse("file://" + musicFolder + "/" + filename);
    				Intent intent = new Intent( Intent.ACTION_VIEW);
    	            intent.setDataAndType(audio, "audio/*");  
    	            startActivity(intent);
    			}
    		});
    	}
    	
    	public void searchSongs(View v) {
    		bindSongsToListView(musicFolder,  editTitle.getText().toString());
    		if ( songs.size() > 0 )
    			songsView.setVisibility(View.VISIBLE);
    		else
    			songsView.setVisibility(View.INVISIBLE);
    			
    	}
    	
    	private  void bindSongsToListView(File musicFolder, String title) {
    		songs = new ArrayList<Song>();
    
    		ArrayList<Map<String,String>> songsMap = new ArrayList<Map<String,String>>();
    		
    		for (File f : musicFolder.listFiles()) {
    			// get MediaMetaData
    			MediaMetadataRetriever md = new MediaMetadataRetriever();
    			md.setDataSource(musicFolder + "/" + f.getName());
    			int secs = Integer.parseInt(md.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) / 1000;
    			int mins= secs / 60;
    			secs =  secs % 60;
    			String singer = md.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
    			if ( singer == null || singer.equals(""))
    				  singer = "Unknown";
    			String songtitle  = md.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
    			if ( songtitle == null )
    				   songtitle = f.getName();
    			String duration = String.format("%02d:%02d", mins,secs);
    			
    			if (songtitle.toUpperCase().contains(title.toUpperCase())) {
    				Song s = new Song();
    				s.setTitle(songtitle);
    				s.setFilename(f.getName());
    				s.setDuration(duration);
    				s.setSinger(singer);
    				songs.add(s);
    
    				Map<String, String> mapobject = convertSongToMap(s);
    				songsMap.add(mapobject);
    			}
    		
    		}
    
    		SimpleAdapter adapter = new SimpleAdapter(this, songsMap, R.layout.song,
    				    new String[] { "title","duration","singer"},
    				     new int[] {  R.id.textTitle, R.id.textDuration, R.id.textSinger} );
    		
    		listSongs.setAdapter(adapter);
    	}
    	
    	public Map<String,String> convertSongToMap(Song s) {
    		
    		HashMap<String, String> map = new HashMap<String,String>();
    		map.put("title", s.getTitle());
    		map.put("duration", s.getDuration());
    		map.put("singer", s.getSinger());
    		return map;
    		
    	}
    }
    
  6. Manifest file is as follows :

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.st.audioplayer"
        android:versionCode="1"
        android:versionName="1.0" >
        <uses-sdk android:minSdkVersion="10" />
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:name=".AudioPlayer"
                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>
    </manifest>
     
  7. Strings are defined in strings.xml as follows:

    res/values/strings.xml

    
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="app_name">Audio Player</string>
    </resources>
    
    
  8. Ensure you place some .MP3 songs into MUSIC folder of SDCARD
  9. Build and run the project using Emulator that supports Android 2.3 (API 10) or higher
  10. Enter string that you want to find in song title and click on Search button. When the selected songs list is displayed, click on the song to play it.