Like Us on Facebook

How to Build a MusicPlayer for Android Device

   Hi, guys welcome back Once again, In this tutorial I am going  discuss about how to build a MusicPlayer for Android device. The Android provides resources for handling media playback, which an apps can use to create an interface between the user and music files, I am going to create basic Music Player for Android . This app basically will read selected Audio file from the list that App present. The App has basic Control  like  pause, play, previous , next and  seekbar . let’s start  the Application.

Read More
How to Play Youtube video in Android Application
How to make Speech to Text Conversion App in Android
How to Create Video Streaming Application in Android

Prerequisites:

  • JDK 7.0 or Above
  • Android Studio 2.0

Steps to Follow:

Step 1: Create a New Android Studio project name PlayMusic.

Step 2: Select minimum API level 17  so that it can support maximum of Android Device available in the google play.

Step 3: Select  Blank  Activity and Give your layout xml name is activity_main and click finish.

Step 4:Inside activity_main.xml  write the following  code
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  android:orientation="vertical"
  tools:context="com.example.playmusic.MainActivity">
 
<ListView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@android:id/list"
  android:layout_weight="1.0"
  />

 <LinearLayout
  android:orientation="vertical"
  android:background="@android:drawable/screen_background_light"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:padding="10dp">
 
 <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="No file Selected"
  android:id="@+id/selecteditem"
  android:ellipsize="middle"
  android:singleLine="true"
  android:gravity="center_horizontal"
  android:textColor="@android:color/darker_gray"
   />
<SeekBar
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/seekBar"
  android:max="100"
  android:paddingBottom="10dp"
  />
 <LinearLayout
  android:orientation="horizontal"
  android:background="@android:drawable/screen_background_light"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:gravity="center"
  >
 <ImageButton
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/previous"
  android:src ="@android:drawable/ic_media_previous"
   />
 <ImageButton
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/play"
  android:src ="@android:drawable/ic_media_play"
  />
<ImageButton
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:id="@+id/next"
   android:src ="@android:drawable/ic_media_next"
   />
 </LinearLayout>
 </LinearLayout>
 </LinearLayout>
 
Step 5: within layout folder  create a new resource file  item.xml  and write the following code inside it.
 
<?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:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="New Text"
  android:ellipsize="end"
  android:singleLine="true"
  android:textSize="20dp"
  android:id="@+id/displayname" />

 <LinearLayout
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">

 <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_weight="1.0"
  android:ellipsize="end"
  android:singleLine="true"
  android:text="New Text"
  android:textSize="18dp"
  android:id="@+id/title" />

 <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:ellipsize="end"
  android:singleLine="true"
  android:gravity="right"
  android:textSize="18dp"
  android:id="@+id/duration" />
</LinearLayout>
</LinearLayout>

Step 6: Inside the manifest.xml write the following code
 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
 
Step 7. Inside MainActivity.java write the following code.
 public class MainActivity extends ListActivity {
 private static final int UPDATE_FREQUENCY = 500;
 private static final int STEP_VALUE = 4000;
 
 private TextView selectedfile = null;
 private SeekBar seekBar = null;
 private MediaPlayer player = null;
 private ImageButton prev = null;
 private ImageButton play = null;
 private ImageButton next = null;
 private MediaCursorAdapter adapter = null;
 
 private boolean isStarted = true;
 private String currentFile = "";
 private boolean isMovingSeekBar = false;
 private final Handler handler = new Handler();
 
 private final Runnable updatePositinRunnable = new Runnable() {
 @Override
 public void run() {
 updatePosition();
 }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 selectedfile = (TextView)findViewById(R.id.selecteditem);
 seekBar =(SeekBar)findViewById(R.id.seekBar);
 prev = (ImageButton)findViewById(R.id.previous);
 play = (ImageButton)findViewById(R.id.play);
 next = (ImageButton)findViewById(R.id.next);
 
 player = new MediaPlayer();
 player.setOnCompletionListener(onCompletion);
 player.setOnErrorListener(onError);
 seekBar.setOnSeekBarChangeListener(seekBarChanged);

 Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,null,null,null);

 if(null!= cursor){
 cursor.moveToFirst();
 adapter = new MediaCursorAdapter(this,R.layout.item ,cursor);
 setListAdapter(adapter);
 prev.setOnClickListener(OnButtonClick);
 play.setOnClickListener(OnButtonClick);
 next.setOnClickListener(OnButtonClick);
 }
 }
 
@Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
 super.onListItemClick(l, v, position, id);
 currentFile = (String) v.getTag();
 startPlay(currentFile);
 }

 private void startPlay(String file) {
 Log.i("Selected: ", file);
 selectedfile.setText(file);
 seekBar.setProgress(0);
 player.stop();
 player.reset();

 try{
 player.setDataSource(file);
 player.prepare();
 player.start();
 }catch (IllegalArgumentException e){
 e.printStackTrace();
 }catch(IllegalStateException e){
 e.printStackTrace();
 }catch (IOException e){
 e.printStackTrace();
 }
 seekBar.setMax(player.getDuration());
 play.setImageResource(android.R.drawable.ic_media_pause);
 updatePosition();
 isStarted = true;
 }
 private void stopPlay(){
 player.stop();
 player.reset();
 play.setImageResource(android.R.drawable.ic_media_play);
 handler.removeCallbacks(updatePositinRunnable);
 seekBar.setProgress(0);
 isStarted = false;
 }

@Override
 protected void onDestroy() {
 super.onDestroy();
 handler.removeCallbacks(updatePositinRunnable);
 player.stop();
 player.reset();
 player.release();
 player = null;
 }

 private void updatePosition() {
 handler.removeCallbacks(updatePositinRunnable);
 seekBar.setProgress(player.getCurrentPosition());
 handler.postDelayed(updatePositinRunnable,UPDATE_FREQUENCY);
 }
 private  View.OnClickListener OnButtonClick = new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 switch(v.getId()){
 case R.id.play:{
 if(player.isPlaying()){
 handler.removeCallbacks(updatePositinRunnable);
 player.pause();
 play.setImageResource(android.R.drawable.ic_media_play);
 }else{
 if(isStarted){
 player.start();
 play.setImageResource(android.R.drawable.ic_media_pause);
 updatePosition();
 }else{
 startPlay(currentFile);
 }
 }
 break;
 }

 case R.id.next:{
 int seekto = player.getCurrentPosition()+ STEP_VALUE;
 if(seekto >player.getDuration())
 seekto =player.getDuration();
 player.pause();
 player.seekTo(seekto);
 player.start();
 break;
 }
 
 case R.id.previous:{
 int seekto = player.getCurrentPosition()- STEP_VALUE;
 if(seekto <0)
 seekto = 0;
 player.pause();
 player.seekTo(seekto);
 player.start();
 break;
 }
 }
 }
 };
 private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
 @Override
 public void onCompletion(MediaPlayer mp) {
 stopPlay();
 };
 };
 private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
 @Override
 public boolean onError(MediaPlayer mp, int what, int extra) {
 return false;
 }
 };
 
 private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
 @Override
 public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
 if(isMovingSeekBar){
 player.seekTo(progress);
 Log.i("OnSeekBarChangeListener","OnProgressChanged");
 }
 }

 @Override
 public void onStartTrackingTouch(SeekBar seekBar) {
 isMovingSeekBar = true;
 }

 @Override
 public void onStopTrackingTouch(SeekBar seekBar) {
 isMovingSeekBar = false;
 }
 };
 }
 
 8. Create a New Class MediaCursorAdapter.java and  add the following code inside it.
 
 public class MediaCursorAdapter extends SimpleCursorAdapter{
 public MediaCursorAdapter(Context context, int layout, Cursor c) {
 super(context, layout, c, new String[]{MediaStore.MediaColumns.DISPLAY_NAME,MediaStore.MediaColumns.TITLE,
 MediaStore.Audio.AudioColumns.DURATION},
 new int[]{R.id.displayname,R.id.title,R.id.duration});
 }

 @Override
 public void bindView(View view, Context context, Cursor cursor) {
 TextView title = (TextView)view.findViewById(R.id.title);
 TextView name = (TextView)view.findViewById(R.id.displayname);
 TextView duration = (TextView)view.findViewById(R.id.duration);
 
 name.setText(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
 title.setText(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
 long durationInMS = Long.parseLong(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
 
 double durationInMin = ((double)durationInMS/1000.0)/60.0;
 durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale( 2, BigDecimal.ROUND_UP).doubleValue();
 duration.setText("" + durationInMin);
 view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
 }
 
@Override
 public View newView(Context context, Cursor cursor, ViewGroup parent) {
 LayoutInflater inflater = LayoutInflater.from(context);
 View v = inflater.inflate(R.layout.item,parent,false);
 bindView(v,context,cursor);
 return v;
 }
 }
 
This completes the coding of this basic  MusicPlayer  application for Android . If you want to improve this application  share your thoughts and ask  any questain in the comment  section below.

Posted By UandBlog

UandBlog is a Global Leading source of Finance, Health, Lifestyle, Technology, Gaming and Programing and other information, it is a fastest growing blog for all , for latest post or information like us on facebook , follow on Twitter, Google+ and Pinterest.

Comments ( 0 )

    Leave a comment..

    Click to login.

    Subscribe Latest Information

    Most Popular Posts

    You May Like Also