Tuesday 13 August 2013

How to play audio in Android


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.
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.


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

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.


<activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>
        </activity>
        <service android:name="PlayAudio"  android:enabled="true">

</service>

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

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!

Screenshot:

No comments: