This tutorial will help you how to create a simple Audio Player application.Normally,when you make a player application based on Activity, it will stop when you exit the application. So, now you will know about a technique using Service to perform playing sound. You can play music when your application is closed.
PlayerService class
public class PlayerService extends Service implements OnCompletionListener,
OnClickListener, OnSeekBarChangeListener {
@Override
public void onCreate() {
// TODO Auto-generated method stub
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);//
utils = new Utilities();
songsListingSD = MainActivity.songsList;
songCurrentDurationLabel = new WeakReference<TextView>(
MainActivity.songCurrentDurationLabel);
super.onCreate();
}
// --------------onStartCommand-----------------------------------------//
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
initUI();
int songIndex = intent.getIntExtra("songIndex", 0);
if (songIndex != currentSongIndex) {
playSong(songIndex);
initNotification(songIndex);
currentSongIndex = songIndex;
} else if (currentSongIndex != -1) {
songTitleLabel.get().setText(
songsListingSD.get(currentSongIndex).get("songTitle"));
if (mp.isPlaying())
btnPlay.get().setImageResource(R.drawable.ic_media_pause);
else
btnPlay.get().setImageResource(R.drawable.ic_media_play);
}
super.onStart(intent, startId);
return START_STICKY;
}
/**
*
*/
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
/**
* Init UI
*/
private void initUI() {
songTitleLabel = new WeakReference<TextView>(MainActivity.songTitle);
songCurrentDurationLabel = new WeakReference<TextView>(
MainActivity.songCurrentDurationLabel);
songTotalDurationLabel = new WeakReference<TextView>(
MainActivity.songTotalDurationLabel);
btnPlay = new WeakReference<ImageView>(MainActivity.btnPlay);
btnForward = new WeakReference<ImageView>(MainActivity.btnForward);
btnBackward = new WeakReference<ImageView>(MainActivity.btnBackward);
btnNext = new WeakReference<ImageView>(MainActivity.btnNext);
btnPrevious = new WeakReference<ImageView>(MainActivity.btnPrevious);
btnRepeat = new WeakReference<ImageButton>(MainActivity.btnRepeat);
btnShuffle = new WeakReference<ImageButton>(MainActivity.btnShuffle);
btnPlay.get().setOnClickListener(this);
btnForward.get().setOnClickListener(this);
btnBackward.get().setOnClickListener(this);
btnNext.get().setOnClickListener(this);
btnPrevious.get().setOnClickListener(this);
btnRepeat.get().setOnClickListener(this);
btnShuffle.get().setOnClickListener(this);
// TODO Auto-generated method stub
songProgressBar = new WeakReference<SeekBar>(
MainActivity.songProgressBar);
songProgressBar.get().setOnSeekBarChangeListener(this);
}
/**
* Function to play a song
*
* @param songIndex
* - index of song
* */
public void playSong(int songIndex) {
// Play song
try {
mp.reset();
mp.setDataSource(songsListingSD.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
// Displaying Song title
String songTitle = songsListingSD.get(songIndex).get("songTitle");
songTitleLabel.get().setText(songTitle);
// Changing Button Image to pause image
btnPlay.get().setImageResource(R.drawable.ic_media_pause);
// set Progress bar values
songProgressBar.get().setProgress(0);
songProgressBar.get().setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Update timer on seekbar
* */
public void updateProgressBar() {
progressBarHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = 0;
try {
totalDuration = mp.getDuration();
} catch (IllegalStateException e) {
e.printStackTrace();
}
long currentDuration = 0;
try {
currentDuration = mp.getCurrentPosition();
} catch (IllegalStateException e) {
e.printStackTrace();
}
// Displaying Total Duration time
songTotalDurationLabel.get().setText(
"" + utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel.get().setText(
"" + utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int) (utils.getProgressPercentage(currentDuration,
totalDuration));
// Log.d("Progress", ""+progress);
songProgressBar.get().setProgress(progress);
// Running this thread after 100 milliseconds
progressBarHandler.postDelayed(this, 100);
// Log.d("AndroidBuildingMusicPlayerActivity","Runable progressbar");
}
};
//--on Seekbar Change Listener
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {
}
/**
* When user starts moving the progress handler
* */
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
progressBarHandler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
* */
public void onStopTrackingTouch(SeekBar seekBar) {
progressBarHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
/**
* On Song Playing completed if repeat is ON play same song again if shuffle
* is ON play random song
* */
public void onCompletion(MediaPlayer arg0) {
// check for repeat is ON or OFF
if (isRepeat) {
// repeat is on play same song again
playSong(currentSongIndex);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsListingSD.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else {
// no repeat or shuffle ON - play next song
if (currentSongIndex < (songsListingSD.size() - 1)) {
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
playSong(0);
currentSongIndex = 0;
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
currentSongIndex = -1;
//Remove progress bar update Hanlder callBacks
progressBarHandler.removeCallbacks(mUpdateTimeTask);
Log.d("Player Service", "Player Service Stopped");
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
}
}
Download sample source code
Media Player Android Sample | 9Android | Android Tips, Tricks, Sources, Reviews