How to play Audio Files in Android with a SeekBar feature and MediaPlayer class



How to play Audio Files in Android with a SeekBar feature and MediaPlayer class



In this tutorial we will explain how to play Audio files in Android using MediaPlayer class We will use resource Id in this tutorial for the playback of audio(.mp3) file. After reading this topic you will be able to make a basic audio player.
Android has MediaPlayer class which holds the functionality that we need to build a music player. In this tutorial we will cover basic methods with their explanations so that user can enhance functionality as per need. In this tutorial we will use “raw” folder to hold the audio file having extension .mp3 for the playback of specified file.
Objective :
  • To provide familiarity about the playback of media files.
  • Implementation of MediaPlayer class for playback.
  • To provide functionality of seekbar to control position of playback.
Classes used to perform this task:
  • MediaPlayer class.
  • Handler class.
  • Runnable class
Introduction to classes:
MediaPlayer Class : In android MediaPlayer class is very powerful which contains wide range of functionality like audio playback, video playback etc. MediaPlayer class contains the following main methods :
  • static MediaPlayer create(Context ctx, int resourceId) : This method is used to set the path of audio file with in context and resourceId will
  • give the id with in asset folder.
  • boolean isPlaying() : This method will tell that MediaPlayer is playing or not.
  • Int getDuration() : This method will return the total duration of current file.
  • Int getCurrentPosition() : This method will return the current postion of playback.
  • void start() : This method will start the playback of MediaPlayer.
  • void pause() : This method will pause the playback of audio file.
  • void stop() : This method will stop the playback of audio file.
  • void reset() : This method will reset the MediaPlayer to uninitialized state.
  • void seekTo(int millisec) : This method will seek the playback to specified seek time in millisec argument.
  • void setLooping(boolean value) : This method will set the repetition of MediaPlayer as per value given, either true or false.
Handler Class : Handler class is used to handle the threads. We have used postDelayed() method to produce delay of 1 second. Here is below the method syntax:
  • public final boolean postDelayed(Runnable object, long delayMilli) : This method is used to introduce the delay in execution of thread which is object of Runnable and delayMilli is the delay time in milliseconds.
  • Runnable Class : Runnable class is used to control the functionality of threads as per need. It contains the following only one method :
  • abstract void run() : This method is used to write the code for implementation of thread.


Steps Involved : Here are the below steps that are required to complete this project.

Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.


Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/text_shown"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="120px"
        android:text=""
        android:textSize="42px" />

    <Button
        android:id="@+id/play_button"
        android:layout_width="120px"
        android:layout_height="60px"
        android:layout_below="@+id/seek_bar"
        android:layout_marginTop="60px"
        android:gravity="center"
        android:text="Play" />

    <Button
        android:id="@+id/pause_button"
       android:layout_width="120px"
        android:layout_height="60px"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/seek_bar"
        android:layout_marginTop="60px"
        android:text="Pause" />

    <SeekBar
        android:id="@+id/seek_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/text_shown"
        android:layout_marginTop="56dp" />

</RelativeLayout>



Step 3 : Open src -> package -> MainActivity.java and add following code : 




package com.gudivada.hemanthsomaraju;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
SeekBar seek_bar;
Button play_button, pause_button;
MediaPlayer player;
TextView text_shown;
Handler seekHandler = new Handler();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

getInit();
seekUpdation();
}

public void getInit() {
seek_bar = (SeekBar) findViewById(R.id.seek_bar);
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
text_shown = (TextView) findViewById(R.id.text_shown);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
player = MediaPlayer.create(this, R.raw.beep);
seek_bar.setMax(player.getDuration());

}

Runnable run = new Runnable() {

@Override
public void run() {
seekUpdation();
}
};

public void seekUpdation() {

seek_bar.setProgress(player.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}

@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
text_shown.setText("Playing...");
player.start();
break;
case R.id.pause_button:
player.pause();
text_shown.setText("Paused...");
}

}


}

Step 4 : Open AndroidManifest.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gudivada.hemanthsomaraju"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.gudivada.hemanthsomaraju.MainActivity"
            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>

Step 5 : Our output will be like this :