articles

Home / DeveloperSection / Articles / Custom Media player in Android

Custom Media player in Android

Manoj Pandey8321 17-Mar-2015

The Android multimedia framework includes support for playing variety of common media types, so that you can easily integrate audio, video and images into your applications using MediaPlayer APIs. Android MediaPlayer class can be used to control playback of audio/video files and streams.

MediaPlayer class can be used to control playback of audio/video files and streams.

Here I am creating example of media player which read data from your sdcard.

1.      Create an android project

2.    Add permission for read external storage data in your application on AndroidManifest.xml file

 

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.androidmediaexample"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="18" />

 

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

         android:name="com.example.androidmediaexample.MainActivity"

            android:configChanges="orientation|screenSize"

            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>

 

3.      Add view in activity_main.xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >

 

    <LinearLayout

        android:layout_width="fill_parent"

        android:layout_height="0dp"

        android:layout_weight=".50"

        android:gravity="center"

        android:orientation="vertical" >

 

        <TextView

            android:id="@+id/mytextview"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:singleLine="true"

            android:text="My Song.mp3"

            android:textSize="18sp" />

 

        <ImageView

            android:layout_width="fill_parent"

            android:layout_height="fill_parent"

            android:padding="10sp"

            android:src="@drawable/ic_launcher" />

    </LinearLayout>

 

    <LinearLayout

        android:layout_width="fill_parent"

        android:layout_height="0dp"

        android:layout_weight=".50"

        android:orientation="vertical" >

 

        <LinearLayout

            android:layout_width="fill_parent"

            android:layout_height="0dp"

            android:layout_weight=".15"

            android:orientation="horizontal" >

 

            <TextView

                android:id="@+id/tvTime"

                android:layout_width="0dp"

                android:layout_height="wrap_content"

                android:layout_weight=".15"

                android:text="0.0" />

 

            <SeekBar

                android:id="@+id/seekBar1"

                android:layout_width="0dp"

                android:layout_height="wrap_content"

                android:layout_weight=".72" />

 

            <TextView

                android:id="@+id/tvLastTime"

                android:layout_width="0dp"

                android:layout_height="wrap_content"

                android:layout_weight=".13"

                android:text="0.0" />

        </LinearLayout>

 

        <LinearLayout

            android:layout_width="fill_parent"

            android:layout_height="0dp"

            android:layout_weight=".35"

            android:orientation="horizontal" >

 

            <ImageButton

                android:id="@+id/btnPrevious"

                android:layout_width="0dp"

                android:layout_height="wrap_content"

                android:layout_weight=".30"

                android:src="@android:drawable/ic_media_rew" />

 

            <ImageButton

                android:id="@+id/btnPaly"

                android:layout_width="0dp"

                android:layout_height="wrap_content"

                android:layout_weight=".30"

                android:src="@android:drawable/ic_media_play" />

 

            <ImageButton

                android:id="@+id/btnPause"

                android:layout_width="0dp"

                android:layout_height="wrap_content"

                android:layout_weight=".30"

                android:src="@android:drawable/ic_media_pause"

                android:visibility="gone" />

 

            <ImageButton

                android:id="@+id/btnNext"

                android:layout_width="0dp"

                android:layout_height="wrap_content"

                android:layout_weight=".30"

                android:src="@android:drawable/ic_media_ff" />

        </LinearLayout>

    </LinearLayout>

 

</LinearLayout>

4.      Add layout xml file for listview name as mylistview.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" >

 

    <ListView

        android:id="@+id/myList"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content" >

    </ListView>

 

</LinearLayout>

 

5.Add layout xml file for listview item  name as listview_item.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="horizontal" >

    <ImageView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginLeft="10sp"

        android:src="@drawable/ic_launcher" />

    <TextView

        android:id="@+id/tvTitle"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginLeft="10sp"

        android:layout_marginTop="20sp" />

</LinearLayout>

 

6. Paste following code in MainActivity.class 

package com.example.androidmediaexample; 

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import java.util.Timer;

import java.util.concurrent.TimeUnit; 

import android.media.MediaPlayer;

import android.net.Uri;

import android.os.Bundle;

import android.os.Environment;

import android.os.Handler;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.Menu;

import android.view.MenuInflater;

import android.view.MenuItem;

import android.view.View;

import android.view.ViewGroup;

import android.view.View.OnClickListener;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.ArrayAdapter;

import android.widget.ImageButton;

import android.widget.ListView;

import android.widget.SeekBar;

import android.widget.SeekBar.OnSeekBarChangeListener;

import android.widget.TextView;

import android.widget.Toast;

 

public class MainActivity extends Activity {

 

     Timer timer;

     List<String> mediaList = new ArrayList<String>();

 

     TextView tvCtime, tvLtime, tvTitle;

     ImageButton imgPlay, imgStop, imgNext, imgPrevious;

     private MediaPlayer mediaPlayer;

     double totaltime = 0.0;

     private Handler durationHandler = new Handler();

     List<String> mySong;

     double curenttime = 0.0;

     SeekBar seekbar;

     boolean seektouch;

     int SongPos = 0;

     String externalStoragePath;

     ArrayAdapter<String> myadapter;

     File targetDir;

     File[] mediaFiles;

 

     @Override

     protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           try {

 

                mySong = new ArrayList<String>();

       externalStoragePath = Environment.getExternalStorageDirectory()

                           .getAbsolutePath();

 

                targetDir = new File(externalStoragePath);

                mediaFiles = targetDir.listFiles();

                scanFiles(mediaFiles);

 

                setContentView(R.layout.activity_main);

                tvTitle = (TextView) findViewById(R.id.mytextview);

                imgPlay = (ImageButton) findViewById(R.id.btnPaly);

                imgStop = (ImageButton) findViewById(R.id.btnPause);

                imgNext = (ImageButton) findViewById(R.id.btnNext);

                seekbar = (SeekBar) findViewById(R.id.seekBar1);

           imgPrevious = (ImageButton) findViewById(R.id.btnPrevious);

              String[] string = mediaList.get(0).toString().split("/");

                String text = string[string.length - 1];

                tvTitle.setText(text);

 

                mediaPlayer = MediaPlayer.create(this,

                           Uri.parse(mediaList.get(SongPos)));

 

                tvCtime = (TextView) findViewById(R.id.tvTime);

                tvLtime = (TextView) findViewById(R.id.tvLastTime);

                timer = new Timer();

                totaltime = mediaPlayer.getDuration();

                imgPlay.setOnClickListener(new OnClickListener() {

 

                     @Override

                     public void onClick(View v) {

                           // TODO Auto-generated method stub

                           try {

 

                              mediaPlayer.reset();

                             SongPos++;

                            setSong(SongPos);

                           totaltime = mediaPlayer.getDuration();

 

                       curenttime = mediaPlayer.getCurrentPosition();

                            seekbar.setMax(mediaPlayer.getDuration());

                                PlaySong();

 

                           } catch (Exception ex) {

      

                           }

                     }

                });

                imgNext.setOnClickListener(new OnClickListener() {

 

                     @Override

                     public void onClick(View v) {

                           // TODO Auto-generated method stub

                           // set next song

                           mediaPlayer.reset();

                           if (SongPos >= mediaList.size() - 1)

                                SongPos = 0;

                           else

                                SongPos++;

                           setSong(SongPos);

                           totaltime = mediaPlayer.getDuration();

                        curenttime = mediaPlayer.getCurrentPosition();

                           seekbar.setMax(mediaPlayer.getDuration());

 

                           PlaySong();

 

                     }

                });

                imgPrevious.setOnClickListener(new OnClickListener() {

 

                     @Override

                     public void onClick(View v) {

                           // TODO Auto-generated method stub

                           // set previous song

                           mediaPlayer.reset();

                           if (SongPos == 0)

                                SongPos = mediaList.size() - 1;

                           else

                                SongPos--;

                           setSong(SongPos);

                           totaltime = mediaPlayer.getDuration();

                         curenttime = mediaPlayer.getCurrentPosition();

                           seekbar.setMax(mediaPlayer.getDuration());

 

                           PlaySong();

                     }

 

                });

     seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

 

                     @Override

                     public void onStopTrackingTouch(SeekBar seekBar) {

                           // TODO Auto-generated method stub

                           seektouch = false;

                     }

 

                     @Override

                     public void onStartTrackingTouch(SeekBar seekBar) {

                           // TODO Auto-generated method stub

                           seektouch = true;

                     }

 

                     @Override

           public void onProgressChanged(SeekBar seekBar, int progress,

                                boolean fromUser) {

                           // TODO Auto-generated method stub

                           // increasing song

                           if (seektouch) {

                                curenttime = progress;

                                mediaPlayer.seekTo((int) curenttime);

                           }

 

                     }

                });

                imgPlay.setOnClickListener(new OnClickListener() {

 

                     @Override

                     public void onClick(View v) {

                           // TODO Auto-generated method stub

                           if (SongPos >= mediaList.size())

                                SongPos = 0;

                         curenttime = mediaPlayer.getCurrentPosition();

                           imgPlay.setVisibility(View.GONE);

                           imgStop.setVisibility(View.VISIBLE);

                           seekbar.setMax(mediaPlayer.getDuration());

 

                           PlaySong();

                     }

                });

                imgStop.setOnClickListener(new OnClickListener() {

 

                     @Override

                     public void onClick(View v) {

                           // TODO Auto-generated method stub

                           imgPlay.setVisibility(View.VISIBLE);

                           imgStop.setVisibility(View.GONE);

                           StopSong();

                     }

                });

           } catch (Exception ex) {

               

           }

     }

 

     @SuppressLint("NewApi")

     public void PlaySong() {

           // start song

           mediaPlayer.start();

           if (mediaPlayer.isPlaying()) {

                imgPlay.setVisibility(View.GONE);

                imgStop.setVisibility(View.VISIBLE);

           }

 

           curenttime = mediaPlayer.getCurrentPosition();

           seekbar.setProgress((int) curenttime);

           // set total time of song

           tvLtime.setText(String.format(

                     "%d:%d ",

           TimeUnit.MILLISECONDS.toMinutes((long) totaltime),

               TimeUnit.MILLISECONDS.toSeconds((long) totaltime)

                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS

                   .toMinutes((long) totaltime))));

           durationHandler.postDelayed(updateSeekBarTime, 100);

 

     }

 

     public void StopSong() {

           // pause song and get time before pause

           curenttime = mediaPlayer.getCurrentPosition();

           mediaPlayer.pause();

     }

 

     private Runnable updateSeekBarTime = new Runnable() {

 

           @SuppressLint("NewApi")

           public void run() {

 

                // get current position

 

                curenttime = mediaPlayer.getCurrentPosition();

 

                // set seekbar progress

 

                seekbar.setProgress((int) curenttime);

 

                // set current timing of song

 

                tvCtime.setText(String.format(

                           "%d:%d ",

                  TimeUnit.MILLISECONDS.toMinutes((long) curenttime),

                  TimeUnit.MILLISECONDS.toSeconds((long) curenttime)

                 - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS

                        .toMinutes((long) curenttime))));

                // repeat yourself that again in 100 miliseconds

 

                durationHandler.postDelayed(this, 100);

 

           }

 

     };

 

     /**

      * scanFiles

      *

      * @param scanFiles

      */

     // scan directories from your sdcard

     public void scanFiles(File[] scanFiles) {

 

           if (scanFiles != null) {

                for (File file : scanFiles) {

 

                     if (file.isDirectory()) {

                           scanFiles(file.listFiles());

 

                     } else {

 

                           addToMediaList(file);

 

                     }

 

                }

           } else {

 

           }

     }

 

     private void addToMediaList(File file) {

 

           if (file != null) {

 

                String path = file.getAbsolutePath();

 

                int index = path.lastIndexOf(".");

                // get extension of folder

               String extn = path.substring(index + 1, path.length());

                // find mp3

                if (extn.equalsIgnoreCase("mp3")) {// ||

 

                     mediaList.add(path);

 

                }

           }

 

     }

 

     public void setSong(int sing) {

           try {

                if (SongPos >= mediaList.size()) {

                     SongPos = 0;

                }

         mediaPlayer.setDataSource(mediaList.get(SongPos).toString());

                mediaPlayer.prepare();

           String[] string = mediaList.get(sing).toString().split("/");

                String text = string[string.length - 1];

                tvTitle.setText(text);

           } catch (IllegalArgumentException e) {

                e.printStackTrace();

           } catch (SecurityException e) {

                e.printStackTrace();

           } catch (IllegalStateException ex) {

                Toast.makeText(getApplicationContext(), ex.toString(),

                           Toast.LENGTH_LONG).show();

           } catch (IOException e) {

                e.printStackTrace();

           }

     }

 

     @Override

     public boolean onCreateOptionsMenu(Menu menu) {

           MenuInflater inflater = getMenuInflater();

           inflater.inflate(R.menu.main, menu);

           return true;

     }

 

     public void MenuClick() {

           try {

                String text;

                mySong.clear();

                for (int i = 0; i < mediaList.size(); i++) {

             String[] string = mediaList.get(i).toString().split("/");

                     text = string[string.length - 1];

                     mySong.add(text);

                }

                // Add list in dialog box

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(

                           MainActivity.this);

                LayoutInflater inflater = getLayoutInflater();

       View convertView = (View) inflater.inflate(R.layout.mylistview,

                           null);

                alertDialog.setView(convertView);

 

       ListView lv = (ListView) convertView.findViewById(R.id.myList);

                final AlertDialog alert = alertDialog.create();

 

                alert.setTitle(" Select song to play...."); // Title

 

       myadapter = new MyAdapter(this, R.layout.listview_item, mySong);

                lv.setAdapter(myadapter);

                lv.setOnItemClickListener(new OnItemClickListener() {

 

                     @Override

             public void onItemClick(AdapterView<?> arg0, View arg1,

                                int pos, long arg3) {

                           // TODO Auto-generated method stub

 

                           SongPos = pos;

                           SongPos++;

                           imgPrevious.performClick();

 

                           alert.cancel();

                           // PlaySong();

                     }

                });

                alert.show();

           } catch (Exception ex) {

 

           }

     }

 

     @Override

     public boolean onOptionsItemSelected(MenuItem item) {

           // Handle item selection

           switch (item.getItemId()) {

           case R.id.action_settings:

                MenuClick();

           default:

                return super.onOptionsItemSelected(item);

           }

     }

 

     private class ViewHolder {

           TextView tvSname;

 

     }

 

     class MyAdapter extends ArrayAdapter<String> {

           LayoutInflater inflater;

           Context myContext;

           List<String> newList;

 

    public MyAdapter(Context context, int resource, List<String> list) {

                super(context, resource, list);

                // TODO Auto-generated constructor stub

 

                myContext = context;

                newList = list;

                inflater = LayoutInflater.from(context);

           }

 

           @Override

  public View getView(final int position, View view, ViewGroup parent) {

                final ViewHolder holder;

                if (view == null) {

                     holder = new ViewHolder();

               view = inflater.inflate(R.layout.listview_item, null);

           holder.tvSname = (TextView) view.findViewById(R.id.tvTitle);

                     view.setTag(holder);

                } else {

                     holder = (ViewHolder) view.getTag();

                }

            holder.tvSname.setText(newList.get(position).toString());

 

                return view;

           }

     }

 

}

 

 

Now run your application  


 Custom Media player in Android

 

You can choose song from click playlist on top right

 Custom Media player in Android

 

 

 

 

 


Updated 26-Oct-2019

Leave Comment

Comments

Liked By