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,
Download Source Code of Android App to Play Audio
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; }
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; } }
The service should be declared with the android manifest file before starting service. This process will be done within
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > ... <service android:name="PlayAudio" android:enabled="true"></service> </application>
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.
<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>
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
Comments are closed for "How to play audio in Android?".
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.
Very nice and simple one.. Thank u so much.. :)
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
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.
Nice article.
[…] a previous tutorial we have seen about how to play audio in android and that will come handy […]
Thank u sir
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
Love it love it…. Doing great job..budy.. Keep it up and Thanks. I read ur 3-4 tutorials .. simply awesome
hi,joe
ur code is gr8,but it gives error in
objPlayer = MediaPlayer.create(this,R.raw.sleepaway);
raw folder can’t be resolved
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
[…] any background Android Service, we need to get reference for using it. Similarly, location service reference will be created using […]
Hi, How do I pause the song
Thanks alot :-)
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 ??
How to loopback song? I want to play song for say 5 times back to back..how to achieve this?
i dont comment generally , but this tutorial made me do this, really thanx alot bro
good, thanks very much, I appreciate your work