Srikanth Technologies

Audio Player

This is an Android application that allows user to search for songs by title and play songs 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 as shown below:

    Song.java

    package com.st.media;
    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. This layout is used by ListView when it displays song.

    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

    activity_audio_player.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. Write code for AudioPlayer Activity

    AudioPlayerActivity.java

    
    package com.st.media;
    
    import android.Manifest;
    import android.app.Activity;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.provider.MediaStore;
    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;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    
    public class AudioPlayerActivity extends Activity {
        ListView listSongs;
        ArrayList<Song> songs;
        EditText editTitle;
        LinearLayout songsView;
        final int STORAGE_PERMISSION = 1;
        boolean permissionGranted  = false;
    
        @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.activity_audio_player);
    
            // 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);
    
            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://" +filename);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(audio, "audio/*");
                    startActivity(intent);
                }
            });
    
            // Need to take permission at runtime if API is >= 23
            if ( Build.VERSION.SDK_INT>= 23) {
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION);
                }
                else
                {
                    permissionGranted = true;
                }
            }
        }
    
        // Called after user responds to permission request
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
           if ( requestCode ==  STORAGE_PERMISSION)
           {
               if ( grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                   permissionGranted = true;
               else
                   permissionGranted = false;
           }
        }
    
        public void searchSongs(View v) {
            if (!permissionGranted  && v != null)
            {
                Toast.makeText(this,"Sorry! You don't have permission to read storage!", Toast.LENGTH_LONG).show();
                return;
            }
            // This is on restore. So just do nothing and return
            if ( v == null && !permissionGranted)
                return;
    
            bindSongsToListView(editTitle.getText().toString());
            if (songs.size() > 0)
                songsView.setVisibility(View.VISIBLE);
            else
                songsView.setVisibility(View.INVISIBLE);
        }
    
        private void bindSongsToListView(String title) {
            songs = new ArrayList<Song>();
            Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
                               MediaStore.Audio.Media.TITLE + " like  ? ",
                               new String[] { "%"  + title + "%"}, null);
            ArrayList<Map<String,String>> songsList = new ArrayList< Map<String,String>>();
    
            while (cursor.moveToNext()) {
                Song s = new Song();
                s.setFilename(cursor.getString(cursor.getColumnIndex( MediaStore.Audio.Media.DATA)));
                s.setTitle( cursor.getString(cursor.getColumnIndex( MediaStore.Audio.Media.TITLE)));
                long duration =  cursor.getLong(cursor.getColumnIndex( MediaStore.Audio.Media.DURATION));
    
                s.setDuration( String.format("%5.2f Mins", (duration / 1000.0) / 60));
                s.setSinger( cursor.getString(cursor.getColumnIndex( MediaStore.Audio.Media.ARTIST)));
                songs.add(s);
    
                Map<String, String> mapobject = convertSongToMap(s);
                songsList.add(mapobject);
            }
    
    
            SimpleAdapter adapter = new SimpleAdapter(this, songsList, 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. Modify manifest to start with AudioPlayerAcivity and list required permissions

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.st.media">
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".AudioPlayerActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
       </application>
    </manifest>
    
  7. Ensure you place some .MP3 songs loaded into your device
  8. Build and run the project using Emulator that supports Android 2.3 (API 10) or higher
  9. 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.