Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

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: Create a new android project in eclipse with name “MediaPlayback” and package name should be “com.nkm.mediaplayback”.

Project name is Media Playback as shown in figure

Figure 1: Project name is Media Playback as shown in figure.

Package name is com.nkm.mediaplayback

Figure 2 : Package name is com.nkm.mediaplayback

Step 2 : Right click on the res folder and choose> New>Folder as shown below:

Choose Folder option as shown in figure.

Figure 3: Choose Folder option as shown in figure.

Step 3 : Give name to the folder “raw” then click on finish as shown below:

Folder name must be raw as shown in figure.

Figure 4 : Folder name must be raw as shown in figure.

Step 4 : Put your desired audio file in this folder.

Win8.mp3 is media file as shown in figure.

Figure 5 : Win8.mp3 is media file as shown in figure.

Step 5

Listing 1: Paste the following code inside the main.xml file.

<?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" />

    <SeekBar
        android:id="@+id/seek_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <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" />

</RelativeLayout>

Step 6

Listing 2: Paste the following code inside the MediaPlaybackActivity.java file.

package com.nkm.mediaplayback;

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 MediaPlaybackActivity 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.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.win8);
		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 7 : Run your project and here is the output:

State of MediaPlayer while playback

Figure 6 : State of MediaPlayer while playback.

State of MediaPlayer while pause

Figure 7 : State of MediaPlayer while pause

Explanantion of above code :

Listing 3: The getInit() method :

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.win8);
		seek_bar.setMax(player.getDuration());

	}

This is user defined method which is used to initialize the “GUI” controls.

Here the following assignment is used for the creation of MediaPlayer class object with name player which assignment of path of the audio file. In this case win8.mp3 is our file which resides in the raw folder under res folder.

player = MediaPlayer.create(this, R.raw.win8);

The setMax() method of Seekbar class : This method will set the total duration of seekbar to the total duration of current audio file.

seek_bar.setMax(player.getDuration());

The run() method : The following code is used to initiate the Runnable class with an object named as run as shown below.

Listing 4: In run() method seekUpdation() method is called which means seekUpdation will called again and again till the playback.

Runnable run = new Runnable() {

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

The seekUpdation() method : This method is used to update the seekbar with delay of 1 second.

public void seekUpdation() {

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

Here in this method the following method will set the seekbar to current position of the playback.

seek_bar.setProgress(player.getCurrentPosition();

And the following method will introduce delay of 1 second in execution of run() method.

seekHandler.postDelayed(run, 1000);

What is Covered ?

In this article we have learned how to play audio files using MediaPlayer class, how to handle seekbar position with Handler class and how to control thread execution in android.

Hope you liked the article, see you next time.

Also read



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login