How to play audio in Android?

This tutorial will help to play audio file in android app. We will create an Android service that will play the audio file. Service is an Android application component and different from Android activity component.

Following steps will help to create an android app to play audio as a service in android mobile,

  1. Create a service by extending Android Service class.
  2. Declare service in AndroidManifest.xml file.
  3. Create an Activity to perform service related functionality.

Download Source Code of Android App to Play Audio

1. Create a subclass for Service class

A new java class named PlayAudio is created which extends Service class. The corresponding callback functions are declared inside the class. The onCreate() method is called before any operations started with the media player instance. So this method deals with the preparatory functionality.  MediaPlayer.create() method is used to promote the state of the MediaPlayer instance from idle to prepared state.

public void onCreate(){
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this,R.raw.sleepaway);
}

Next the onStartCommand() command is used to start the media player. This method will be invoked when the startService method is called from other application component. Here an activity is used to trigger the service and also to stop the running services. If the long running service is not at all started, then the error message is written into the log.

public int onStartCommand(Intent intent, int flags, int startId){
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
}
return 1;
}

And then, the service will be stopped temporarily or permanently by the onPause() and onStop() methods respectively. The onPause() method will be called when the service is temporarily stopped which doesn’t mean that it is not completely closed. And the onStop() method will be called when all components bound with the service are closed or if there is any call for stopService() or stopSelf() methods. The coding for the onPause() and onStop() as follows.

public void onStop(){
objPlayer.stop();
objPlayer.release();
}
public void onPause(){
objPlayer.stop();
objPlayer.release();
}

Finally, an inherited method from Service base class named onBind() should be implemented with the class. If the service is bounded with any other component, then this method will return corresponding parameter. Otherwise, it will return null value as follows.

@Override
public IBinder onBind(Intent objIndent) {
return null;
}

PlayAudio.java – The entire code for Android service class to play audio

package com.javapapers.android.playaudio;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

public class PlayAudio extends Service{
private static final String LOGCAT = null;
MediaPlayer objPlayer;

public void onCreate(){
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this,R.raw.sleepaway);
}

public int onStartCommand(Intent intent, int flags, int startId){
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
}
return 1;
}

public void onStop(){
objPlayer.stop();
objPlayer.release();
}

public void onPause(){
objPlayer.stop();
objPlayer.release();
}
public void onDestroy(){
objPlayer.stop();
objPlayer.release();
}
@Override
public IBinder onBind(Intent objIndent) {
return null;
}
}

2. Declare service in AndroidManifest.xml file

The service should be declared with the android manifest file before starting service. This process will be done within tags as follows.

<application
	android:icon="@drawable/ic_launcher"
	android:label="@string/app_name"
	android:theme="@style/AppTheme" >
...
<service android:name="PlayAudio"  android:enabled="true"></service>
</application>

3. Create Activity to perform service related functionality

An activity is created which has two button with its graphical layout. These buttons are named as play and stop to start the background music and to pause respectively. In the onClick event of these button refer the event handlers named startAudio and stopAudio. These Event handlers are defined with the corresponding java class associated with the activity component. The startService() and stopService() are invoked from those handler to work with the services call back methods discussed earlier. The graphical layout file and the class file are coded as follows.

activity_main.xml

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

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:onClick="playAudio"
android:text="Play" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_marginLeft="24dp"
android:layout_toRightOf="@+id/button1"
android:onClick="stopAudio"
android:text="Stop" />

</RelativeLayout>

MainActivity.java

package com.javapapers.android.playaudio;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.content.Intent;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

public void playAudio(View view) {
Intent objIntent = new Intent(this, PlayAudio.class);
startService(objIntent);
}

public void stopAudio(View view) {
Intent objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);    
}
}

Run the program and hear the music!

Download Source Code of Android App to Play Audio

This Android tutorial was added on 30/11/2012.

«

»

Comments on "How to play audio in Android?" Tutorial:

  1. Aparna says:

    Even the way you compose your articles is like music!

    Lovely blog you have got. Very rare to see a technical blog written so lively, lightly and enjoyably.

  2. Rashi.. Coorg..] says:

    Very nice and simple one.. Thank u so much.. :)

  3. David Svarrer says:

    You’re a great inspiration. We are running an Android Boot Camp right from 03 Dec 2012 here in Nairobi, Kenya, and we are posting your articles amongst many others for the youngsters to be inspired and see the possibilities. Joe, you are great.

    David Svarrer

    • Joe says:

      Thank you David Svarrer for the wishes. Good luck for the boot camp.

      I have gone through your website, you are doing great work through Digital Age Institute.

  4. Prashant S says:

    Nice article.

  5. [...] a previous tutorial we have seen about how to play audio in android and that will come handy [...]

  6. salman says:

    Thank u sir

  7. Nagarajan says:

    Thanks for your excellent tutorial.I have one doubt sir. mediaplayer app is working fine for me even after the app closes.but while i again opens and try to stop the song,media player wont stop(Says media player is in state o) but song is running in background.i use mediaplayer.stop() only. May i have to do anything in onresume and onpause events?Please tell me sir.i am struggling in this point.

    Thanks in advance

  8. Vishal says:

    Love it love it…. Doing great job..budy.. Keep it up and Thanks. I read ur 3-4 tutorials .. simply awesome

  9. Roshni says:

    hi,joe
    ur code is gr8,but it gives error in
    objPlayer = MediaPlayer.create(this,R.raw.sleepaway);
    raw folder can’t be resolved

  10. Anonymous says:

    it’s a great tutorial. please tell me how i use media player as a stream radio.
    here is my code inside onCreate method.
    objPlayer= new MediaPlayer(); objPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC) objPlayer.setDataSource(myUrl); objPlayer.prepareAsync();
    thnaks

  11. [...] any background Android Service, we need to get reference for using it. Similarly, location service reference will be created using [...]

  12. jean says:

    Hi, How do I pause the song

  13. Anonymous says:

    Thanks alot :-)

  14. Uzair says:

    well , application is very good working on StartService and stopService, but the problem is about Pause Service, Pause also working as Stop ,, soo need solution for this .. also
    if i want to move nxt song, and previous then what services are used , and how ??

  15. Rishabh says:

    How to loopback song? I want to play song for say 5 times back to back..how to achieve this?

  16. Sheikh Ozair says:

    i dont comment generally , but this tutorial made me do this, really thanx alot bro

Your Comment

↑ Go to top