play audio in AndroidThis 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.

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.

publicint 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");
}
return1;
}

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.

publicvoid onStop()
{
objPlayer.stop();
objPlayer.release();
}
publicvoid 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.

@OverridepublicIBinder onBind(Intent objIndent){returnnull;}

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

package com.latesttutorials.android.playaudio;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
publicclassPlayAudioextendsService
{
privatestaticfinalString LOGCAT =null;MediaPlayer objPlayer;
publicvoid onCreate()
{
super.onCreate();
Log.d(LOGCAT,"Service Started!");
objPlayer =MediaPlayer.create(this,R.raw.sleepaway);
}
publicint 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");
}
return1;
}
publicvoid onStop()
{
objPlayer.stop();
objPlayer.release();
}
publicvoid onPause()
{
objPlayer.stop();
objPlayer.release();
}
publicvoid onDestroy()
{
objPlayer.stop();
objPlayer.release();
}
@OverridepublicIBinder onBind(Intent objIndent)
{
returnnull;
}
}

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.

<applicationandroid:icon="@drawable/ic_launcher"
android:label="@string/app_name"android:theme="@style/AppTheme">
...
<serviceandroid: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

<RelativeLayoutxmlns: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">
<Buttonandroid: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"/>
<Buttonandroid: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.latesttutorials.android.playaudio;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.content.Intent;
publicclassMainActivityextendsActivity
{
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
publicboolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
returntrue;
}
publicvoid playAudio(View view)
{
Intent objIntent =newIntent(this,PlayAudio.class);
startService(objIntent);
}
publicvoid stopAudio(View view)
{
Intent objIntent =newIntent(this,PlayAudio.class);
stopService(objIntent);
}
}

Run the program and hear the music!

Download Source Code of Android App to Play Audio

 

Leave a Reply

Your email address will not be published. Required fields are marked *