How to add the service for my custom media player in android
I have done my custom media player for streaming audio file from server but i don't know how to add the background service to this media player and like to add in the notification bar too from which we can control and close the audio player itself. Please tell me anyone how to make a service for custom streaming - audio player.
My Code Part :
public class AudioStream extends Activity implements View.OnClickListener,
OnTouchListener, OnCompletionListener, OnBufferingUpdateListener,
OnPreparedListener, SeekBar.OnSeekBarChangeListener, OnErrorListener, OnInfoListener
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
private MediaPlayer mediaPlayer;
private TextView totalDuration, currentDuration;
private Handler mHandler;
private int mediaFileLengthInMilliseconds;
private Utils utils;
private String streamUrl, thumbImgUrl;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_stream);
// Getting Stream Url from the preview activity
if(getIntent()!= null)
streamUrl = getIntent().getStringExtra("normalurl");
thumbImgUrl = getIntent().getStringExtra("thumburl");
initView();
/** This method initialise all the views in project */
private void initView()
// this handler using for update the seekbar progress and current time duration of the file
mHandler = new Handler();
utils = new Utils();
buttonPlayPause = (ImageButton) findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
currentDuration = (TextView) findViewById(R.id.musicCurrentLoc);
totalDuration = (TextView) findViewById(R.id.musicDuration);
mediaPlayer = new MediaPlayer();
// start the asyntask to start the streaming and start the player
AudioStreamingAsyntask audioAsyn = new AudioStreamingAsyntask();
audioAsyn.execute(streamUrl);
seekBarProgress.setOnSeekBarChangeListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
/**
* Set the URL inot Media player
*/
public void setDataSource(String url)
try
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
catch (IllegalArgumentException e)
e.printStackTrace();
catch (IllegalStateException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
@Override
public void onClick(View v)
if (v.getId() == R.id.ButtonTestPlayPause)
/**
* ImageButton onClick event handler. Method which start/pause
* mediaplayer playing
*/
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
else
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public boolean onTouch(View v, MotionEvent event)
mHandler.removeCallbacks(mUpdateTimeTask);
if (v.getId() == R.id.SeekBarTestPlay)
/**
* Seekbar onTouch event handler. Method which seeks MediaPlayer to
* seekBar primary progress position
*/
if (mediaPlayer.isPlaying())
SeekBar sb = (SeekBar) v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
* sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
updateProgressBar();
return false;
@Override
public void onCompletion(MediaPlayer mp)
/**
* MediaPlayer onCompletion event handler. Method which calls then song
* playing is complete
*/
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
/**
* Method which updates the SeekBar secondary progress by current song
* loading from URL position
*/
seekBarProgress.setSecondaryProgress(percent);
@Override
public void onPrepared(MediaPlayer mp)
// TODO Auto-generated method stub
mediaFileLengthInMilliseconds = mediaPlayer.getDuration();
//primarySeekBarProgressUpdater();
updateProgressBar();
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
else
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public void onBackPressed()
// TODO Auto-generated method stub
super.onBackPressed();
if (mediaPlayer != null)
mediaPlayer.stop();
mediaPlayer = null;
mHandler.removeCallbacks(mUpdateTimeTask);
@Override
protected void onDestroy()
// TODO Auto-generated method stub
super.onDestroy();
mHandler.removeCallbacks(mUpdateTimeTask);
//mHandler = null;
/**
* Update timer on seekbar
* */
public void updateProgressBar()
mHandler.postDelayed(mUpdateTimeTask, 1000);
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable()
public void run()
long mtotalDuration = mediaPlayer.getDuration();
long mcurrentDuration = mediaPlayer.getCurrentPosition();
// Displaying time completed playing
currentDuration.setText(""
+ utils.milliSecondsToTimer(mcurrentDuration));
// Displaying Total Duration time
totalDuration.setText(""
+ utils.milliSecondsToTimer(mtotalDuration));
// Updating progress bar
int progress = (int) (utils.getProgressPercentage(mcurrentDuration,
mtotalDuration));
// Log.d("Progress", ""+progress);
seekBarProgress.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
;
@Override
public void onProgressChanged(SeekBar seekbar, int position, boolean arg2)
// TODO Auto-generated method stub
if(!mediaPlayer.isPlaying())
mediaPlayer.start();
long mcurrentDuration = mediaPlayer.getCurrentPosition();
//position = utils.progressToTimer(seekbar.getProgress(), totalDuration);
currentDuration.setText(""
+ utils.milliSecondsToTimer(mcurrentDuration));
@Override
public void onStartTrackingTouch(SeekBar arg0)
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
@Override
public void onStopTrackingTouch(SeekBar seekBar)
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mediaPlayer.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
// forward or backward to certain seconds
mediaPlayer.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
@Override
public boolean onError(MediaPlayer mp, int what, int extra)
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
//sb.append("Media Player Error: ");
switch (what)
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Media Error Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
//sb.append(" (" + what + ") ");
if(extra == -1004)
sb.append("Network interruption occured : "+extra);
else if(extra == -110)
sb.append("Media Player Error : "+extra);
else
sb.append("Unknown Media Player Error");
//sb.append(extra);
PreviewActivity.backClick = false;
showErrorDialog("Cannot play Audio", sb.toString());
return true;
@SuppressWarnings("deprecation")
void showErrorDialog(String title, String message)
try
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Icon to Dialog
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
// Setting Background color to Dialog
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int which)
// Write your code here to execute after dialog closed
dialog.dismiss();
finish();
onBackPressed();
);
// Showing Alert Message
if(this!= null && !this.isFinishing())
alertDialog.show();
catch(IllegalArgumentException Iae)
Iae.printStackTrace();
// handle the info and warning of the media player
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
//sb.append("Media Player Error: ");
if(Constants.DEBUG)Log.d("AudioStream", "Info : "+what+" "+extra);
switch (what)
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Media Error Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
//sb.append(" (" + what + ") ");
if(extra == -1004)
sb.append("Network interruption occured : "+extra);
else if(extra == -110)
sb.append("Media Player Error : "+extra);
else
sb.append("Unknown Media Player Error");
//sb.append(extra);
PreviewActivity.backClick = false;
showErrorDialog("Cannot play Audio", sb.toString());
return true;
class AudioStreamingAsyntask extends AsyncTask<String, Integer, Result>
ProgressDialog mProgressDialog;
@Override
protected void onPreExecute()
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(AudioStream.this);
mProgressDialog.setMessage("Loading...");
if(mProgressDialog != null)
mProgressDialog.show();
@Override
protected Result doInBackground(String... params)
// TODO Auto-generated method stub
String url = params[0];
setDataSource(url);
return null;
@Override
protected void onPostExecute(Result result)
// TODO Auto-generated method stub
super.onPostExecute(result);
mProgressDialog.dismiss();
mProgressDialog = null;
Thanks in Advance.
add a comment |
I have done my custom media player for streaming audio file from server but i don't know how to add the background service to this media player and like to add in the notification bar too from which we can control and close the audio player itself. Please tell me anyone how to make a service for custom streaming - audio player.
My Code Part :
public class AudioStream extends Activity implements View.OnClickListener,
OnTouchListener, OnCompletionListener, OnBufferingUpdateListener,
OnPreparedListener, SeekBar.OnSeekBarChangeListener, OnErrorListener, OnInfoListener
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
private MediaPlayer mediaPlayer;
private TextView totalDuration, currentDuration;
private Handler mHandler;
private int mediaFileLengthInMilliseconds;
private Utils utils;
private String streamUrl, thumbImgUrl;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_stream);
// Getting Stream Url from the preview activity
if(getIntent()!= null)
streamUrl = getIntent().getStringExtra("normalurl");
thumbImgUrl = getIntent().getStringExtra("thumburl");
initView();
/** This method initialise all the views in project */
private void initView()
// this handler using for update the seekbar progress and current time duration of the file
mHandler = new Handler();
utils = new Utils();
buttonPlayPause = (ImageButton) findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
currentDuration = (TextView) findViewById(R.id.musicCurrentLoc);
totalDuration = (TextView) findViewById(R.id.musicDuration);
mediaPlayer = new MediaPlayer();
// start the asyntask to start the streaming and start the player
AudioStreamingAsyntask audioAsyn = new AudioStreamingAsyntask();
audioAsyn.execute(streamUrl);
seekBarProgress.setOnSeekBarChangeListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
/**
* Set the URL inot Media player
*/
public void setDataSource(String url)
try
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
catch (IllegalArgumentException e)
e.printStackTrace();
catch (IllegalStateException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
@Override
public void onClick(View v)
if (v.getId() == R.id.ButtonTestPlayPause)
/**
* ImageButton onClick event handler. Method which start/pause
* mediaplayer playing
*/
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
else
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public boolean onTouch(View v, MotionEvent event)
mHandler.removeCallbacks(mUpdateTimeTask);
if (v.getId() == R.id.SeekBarTestPlay)
/**
* Seekbar onTouch event handler. Method which seeks MediaPlayer to
* seekBar primary progress position
*/
if (mediaPlayer.isPlaying())
SeekBar sb = (SeekBar) v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
* sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
updateProgressBar();
return false;
@Override
public void onCompletion(MediaPlayer mp)
/**
* MediaPlayer onCompletion event handler. Method which calls then song
* playing is complete
*/
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
/**
* Method which updates the SeekBar secondary progress by current song
* loading from URL position
*/
seekBarProgress.setSecondaryProgress(percent);
@Override
public void onPrepared(MediaPlayer mp)
// TODO Auto-generated method stub
mediaFileLengthInMilliseconds = mediaPlayer.getDuration();
//primarySeekBarProgressUpdater();
updateProgressBar();
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
else
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public void onBackPressed()
// TODO Auto-generated method stub
super.onBackPressed();
if (mediaPlayer != null)
mediaPlayer.stop();
mediaPlayer = null;
mHandler.removeCallbacks(mUpdateTimeTask);
@Override
protected void onDestroy()
// TODO Auto-generated method stub
super.onDestroy();
mHandler.removeCallbacks(mUpdateTimeTask);
//mHandler = null;
/**
* Update timer on seekbar
* */
public void updateProgressBar()
mHandler.postDelayed(mUpdateTimeTask, 1000);
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable()
public void run()
long mtotalDuration = mediaPlayer.getDuration();
long mcurrentDuration = mediaPlayer.getCurrentPosition();
// Displaying time completed playing
currentDuration.setText(""
+ utils.milliSecondsToTimer(mcurrentDuration));
// Displaying Total Duration time
totalDuration.setText(""
+ utils.milliSecondsToTimer(mtotalDuration));
// Updating progress bar
int progress = (int) (utils.getProgressPercentage(mcurrentDuration,
mtotalDuration));
// Log.d("Progress", ""+progress);
seekBarProgress.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
;
@Override
public void onProgressChanged(SeekBar seekbar, int position, boolean arg2)
// TODO Auto-generated method stub
if(!mediaPlayer.isPlaying())
mediaPlayer.start();
long mcurrentDuration = mediaPlayer.getCurrentPosition();
//position = utils.progressToTimer(seekbar.getProgress(), totalDuration);
currentDuration.setText(""
+ utils.milliSecondsToTimer(mcurrentDuration));
@Override
public void onStartTrackingTouch(SeekBar arg0)
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
@Override
public void onStopTrackingTouch(SeekBar seekBar)
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mediaPlayer.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
// forward or backward to certain seconds
mediaPlayer.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
@Override
public boolean onError(MediaPlayer mp, int what, int extra)
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
//sb.append("Media Player Error: ");
switch (what)
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Media Error Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
//sb.append(" (" + what + ") ");
if(extra == -1004)
sb.append("Network interruption occured : "+extra);
else if(extra == -110)
sb.append("Media Player Error : "+extra);
else
sb.append("Unknown Media Player Error");
//sb.append(extra);
PreviewActivity.backClick = false;
showErrorDialog("Cannot play Audio", sb.toString());
return true;
@SuppressWarnings("deprecation")
void showErrorDialog(String title, String message)
try
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Icon to Dialog
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
// Setting Background color to Dialog
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int which)
// Write your code here to execute after dialog closed
dialog.dismiss();
finish();
onBackPressed();
);
// Showing Alert Message
if(this!= null && !this.isFinishing())
alertDialog.show();
catch(IllegalArgumentException Iae)
Iae.printStackTrace();
// handle the info and warning of the media player
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
//sb.append("Media Player Error: ");
if(Constants.DEBUG)Log.d("AudioStream", "Info : "+what+" "+extra);
switch (what)
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Media Error Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
//sb.append(" (" + what + ") ");
if(extra == -1004)
sb.append("Network interruption occured : "+extra);
else if(extra == -110)
sb.append("Media Player Error : "+extra);
else
sb.append("Unknown Media Player Error");
//sb.append(extra);
PreviewActivity.backClick = false;
showErrorDialog("Cannot play Audio", sb.toString());
return true;
class AudioStreamingAsyntask extends AsyncTask<String, Integer, Result>
ProgressDialog mProgressDialog;
@Override
protected void onPreExecute()
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(AudioStream.this);
mProgressDialog.setMessage("Loading...");
if(mProgressDialog != null)
mProgressDialog.show();
@Override
protected Result doInBackground(String... params)
// TODO Auto-generated method stub
String url = params[0];
setDataSource(url);
return null;
@Override
protected void onPostExecute(Result result)
// TODO Auto-generated method stub
super.onPostExecute(result);
mProgressDialog.dismiss();
mProgressDialog = null;
Thanks in Advance.
Go to official docs for best explanation
– M D
May 13 '14 at 6:01
Thank for your comment, could u please give some example code depends on my code
– siva
May 13 '14 at 6:07
all the required code snippet available in that link.
– M D
May 13 '14 at 6:10
i don't know how to integrate those code into my code part, i getting some difficulties while integrating.So please bring some example or tutorials depends upon my code that would be helpful
– siva
May 14 '14 at 5:37
add a comment |
I have done my custom media player for streaming audio file from server but i don't know how to add the background service to this media player and like to add in the notification bar too from which we can control and close the audio player itself. Please tell me anyone how to make a service for custom streaming - audio player.
My Code Part :
public class AudioStream extends Activity implements View.OnClickListener,
OnTouchListener, OnCompletionListener, OnBufferingUpdateListener,
OnPreparedListener, SeekBar.OnSeekBarChangeListener, OnErrorListener, OnInfoListener
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
private MediaPlayer mediaPlayer;
private TextView totalDuration, currentDuration;
private Handler mHandler;
private int mediaFileLengthInMilliseconds;
private Utils utils;
private String streamUrl, thumbImgUrl;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_stream);
// Getting Stream Url from the preview activity
if(getIntent()!= null)
streamUrl = getIntent().getStringExtra("normalurl");
thumbImgUrl = getIntent().getStringExtra("thumburl");
initView();
/** This method initialise all the views in project */
private void initView()
// this handler using for update the seekbar progress and current time duration of the file
mHandler = new Handler();
utils = new Utils();
buttonPlayPause = (ImageButton) findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
currentDuration = (TextView) findViewById(R.id.musicCurrentLoc);
totalDuration = (TextView) findViewById(R.id.musicDuration);
mediaPlayer = new MediaPlayer();
// start the asyntask to start the streaming and start the player
AudioStreamingAsyntask audioAsyn = new AudioStreamingAsyntask();
audioAsyn.execute(streamUrl);
seekBarProgress.setOnSeekBarChangeListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
/**
* Set the URL inot Media player
*/
public void setDataSource(String url)
try
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
catch (IllegalArgumentException e)
e.printStackTrace();
catch (IllegalStateException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
@Override
public void onClick(View v)
if (v.getId() == R.id.ButtonTestPlayPause)
/**
* ImageButton onClick event handler. Method which start/pause
* mediaplayer playing
*/
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
else
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public boolean onTouch(View v, MotionEvent event)
mHandler.removeCallbacks(mUpdateTimeTask);
if (v.getId() == R.id.SeekBarTestPlay)
/**
* Seekbar onTouch event handler. Method which seeks MediaPlayer to
* seekBar primary progress position
*/
if (mediaPlayer.isPlaying())
SeekBar sb = (SeekBar) v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
* sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
updateProgressBar();
return false;
@Override
public void onCompletion(MediaPlayer mp)
/**
* MediaPlayer onCompletion event handler. Method which calls then song
* playing is complete
*/
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
/**
* Method which updates the SeekBar secondary progress by current song
* loading from URL position
*/
seekBarProgress.setSecondaryProgress(percent);
@Override
public void onPrepared(MediaPlayer mp)
// TODO Auto-generated method stub
mediaFileLengthInMilliseconds = mediaPlayer.getDuration();
//primarySeekBarProgressUpdater();
updateProgressBar();
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
else
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public void onBackPressed()
// TODO Auto-generated method stub
super.onBackPressed();
if (mediaPlayer != null)
mediaPlayer.stop();
mediaPlayer = null;
mHandler.removeCallbacks(mUpdateTimeTask);
@Override
protected void onDestroy()
// TODO Auto-generated method stub
super.onDestroy();
mHandler.removeCallbacks(mUpdateTimeTask);
//mHandler = null;
/**
* Update timer on seekbar
* */
public void updateProgressBar()
mHandler.postDelayed(mUpdateTimeTask, 1000);
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable()
public void run()
long mtotalDuration = mediaPlayer.getDuration();
long mcurrentDuration = mediaPlayer.getCurrentPosition();
// Displaying time completed playing
currentDuration.setText(""
+ utils.milliSecondsToTimer(mcurrentDuration));
// Displaying Total Duration time
totalDuration.setText(""
+ utils.milliSecondsToTimer(mtotalDuration));
// Updating progress bar
int progress = (int) (utils.getProgressPercentage(mcurrentDuration,
mtotalDuration));
// Log.d("Progress", ""+progress);
seekBarProgress.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
;
@Override
public void onProgressChanged(SeekBar seekbar, int position, boolean arg2)
// TODO Auto-generated method stub
if(!mediaPlayer.isPlaying())
mediaPlayer.start();
long mcurrentDuration = mediaPlayer.getCurrentPosition();
//position = utils.progressToTimer(seekbar.getProgress(), totalDuration);
currentDuration.setText(""
+ utils.milliSecondsToTimer(mcurrentDuration));
@Override
public void onStartTrackingTouch(SeekBar arg0)
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
@Override
public void onStopTrackingTouch(SeekBar seekBar)
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mediaPlayer.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
// forward or backward to certain seconds
mediaPlayer.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
@Override
public boolean onError(MediaPlayer mp, int what, int extra)
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
//sb.append("Media Player Error: ");
switch (what)
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Media Error Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
//sb.append(" (" + what + ") ");
if(extra == -1004)
sb.append("Network interruption occured : "+extra);
else if(extra == -110)
sb.append("Media Player Error : "+extra);
else
sb.append("Unknown Media Player Error");
//sb.append(extra);
PreviewActivity.backClick = false;
showErrorDialog("Cannot play Audio", sb.toString());
return true;
@SuppressWarnings("deprecation")
void showErrorDialog(String title, String message)
try
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Icon to Dialog
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
// Setting Background color to Dialog
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int which)
// Write your code here to execute after dialog closed
dialog.dismiss();
finish();
onBackPressed();
);
// Showing Alert Message
if(this!= null && !this.isFinishing())
alertDialog.show();
catch(IllegalArgumentException Iae)
Iae.printStackTrace();
// handle the info and warning of the media player
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
//sb.append("Media Player Error: ");
if(Constants.DEBUG)Log.d("AudioStream", "Info : "+what+" "+extra);
switch (what)
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Media Error Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
//sb.append(" (" + what + ") ");
if(extra == -1004)
sb.append("Network interruption occured : "+extra);
else if(extra == -110)
sb.append("Media Player Error : "+extra);
else
sb.append("Unknown Media Player Error");
//sb.append(extra);
PreviewActivity.backClick = false;
showErrorDialog("Cannot play Audio", sb.toString());
return true;
class AudioStreamingAsyntask extends AsyncTask<String, Integer, Result>
ProgressDialog mProgressDialog;
@Override
protected void onPreExecute()
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(AudioStream.this);
mProgressDialog.setMessage("Loading...");
if(mProgressDialog != null)
mProgressDialog.show();
@Override
protected Result doInBackground(String... params)
// TODO Auto-generated method stub
String url = params[0];
setDataSource(url);
return null;
@Override
protected void onPostExecute(Result result)
// TODO Auto-generated method stub
super.onPostExecute(result);
mProgressDialog.dismiss();
mProgressDialog = null;
Thanks in Advance.
I have done my custom media player for streaming audio file from server but i don't know how to add the background service to this media player and like to add in the notification bar too from which we can control and close the audio player itself. Please tell me anyone how to make a service for custom streaming - audio player.
My Code Part :
public class AudioStream extends Activity implements View.OnClickListener,
OnTouchListener, OnCompletionListener, OnBufferingUpdateListener,
OnPreparedListener, SeekBar.OnSeekBarChangeListener, OnErrorListener, OnInfoListener
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
private MediaPlayer mediaPlayer;
private TextView totalDuration, currentDuration;
private Handler mHandler;
private int mediaFileLengthInMilliseconds;
private Utils utils;
private String streamUrl, thumbImgUrl;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_stream);
// Getting Stream Url from the preview activity
if(getIntent()!= null)
streamUrl = getIntent().getStringExtra("normalurl");
thumbImgUrl = getIntent().getStringExtra("thumburl");
initView();
/** This method initialise all the views in project */
private void initView()
// this handler using for update the seekbar progress and current time duration of the file
mHandler = new Handler();
utils = new Utils();
buttonPlayPause = (ImageButton) findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
currentDuration = (TextView) findViewById(R.id.musicCurrentLoc);
totalDuration = (TextView) findViewById(R.id.musicDuration);
mediaPlayer = new MediaPlayer();
// start the asyntask to start the streaming and start the player
AudioStreamingAsyntask audioAsyn = new AudioStreamingAsyntask();
audioAsyn.execute(streamUrl);
seekBarProgress.setOnSeekBarChangeListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
/**
* Set the URL inot Media player
*/
public void setDataSource(String url)
try
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
catch (IllegalArgumentException e)
e.printStackTrace();
catch (IllegalStateException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
@Override
public void onClick(View v)
if (v.getId() == R.id.ButtonTestPlayPause)
/**
* ImageButton onClick event handler. Method which start/pause
* mediaplayer playing
*/
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
else
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public boolean onTouch(View v, MotionEvent event)
mHandler.removeCallbacks(mUpdateTimeTask);
if (v.getId() == R.id.SeekBarTestPlay)
/**
* Seekbar onTouch event handler. Method which seeks MediaPlayer to
* seekBar primary progress position
*/
if (mediaPlayer.isPlaying())
SeekBar sb = (SeekBar) v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
* sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
updateProgressBar();
return false;
@Override
public void onCompletion(MediaPlayer mp)
/**
* MediaPlayer onCompletion event handler. Method which calls then song
* playing is complete
*/
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
/**
* Method which updates the SeekBar secondary progress by current song
* loading from URL position
*/
seekBarProgress.setSecondaryProgress(percent);
@Override
public void onPrepared(MediaPlayer mp)
// TODO Auto-generated method stub
mediaFileLengthInMilliseconds = mediaPlayer.getDuration();
//primarySeekBarProgressUpdater();
updateProgressBar();
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
else
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.playicon_large);
@Override
public void onBackPressed()
// TODO Auto-generated method stub
super.onBackPressed();
if (mediaPlayer != null)
mediaPlayer.stop();
mediaPlayer = null;
mHandler.removeCallbacks(mUpdateTimeTask);
@Override
protected void onDestroy()
// TODO Auto-generated method stub
super.onDestroy();
mHandler.removeCallbacks(mUpdateTimeTask);
//mHandler = null;
/**
* Update timer on seekbar
* */
public void updateProgressBar()
mHandler.postDelayed(mUpdateTimeTask, 1000);
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable()
public void run()
long mtotalDuration = mediaPlayer.getDuration();
long mcurrentDuration = mediaPlayer.getCurrentPosition();
// Displaying time completed playing
currentDuration.setText(""
+ utils.milliSecondsToTimer(mcurrentDuration));
// Displaying Total Duration time
totalDuration.setText(""
+ utils.milliSecondsToTimer(mtotalDuration));
// Updating progress bar
int progress = (int) (utils.getProgressPercentage(mcurrentDuration,
mtotalDuration));
// Log.d("Progress", ""+progress);
seekBarProgress.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
;
@Override
public void onProgressChanged(SeekBar seekbar, int position, boolean arg2)
// TODO Auto-generated method stub
if(!mediaPlayer.isPlaying())
mediaPlayer.start();
long mcurrentDuration = mediaPlayer.getCurrentPosition();
//position = utils.progressToTimer(seekbar.getProgress(), totalDuration);
currentDuration.setText(""
+ utils.milliSecondsToTimer(mcurrentDuration));
@Override
public void onStartTrackingTouch(SeekBar arg0)
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
@Override
public void onStopTrackingTouch(SeekBar seekBar)
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mediaPlayer.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
// forward or backward to certain seconds
mediaPlayer.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
@Override
public boolean onError(MediaPlayer mp, int what, int extra)
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
//sb.append("Media Player Error: ");
switch (what)
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Media Error Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
//sb.append(" (" + what + ") ");
if(extra == -1004)
sb.append("Network interruption occured : "+extra);
else if(extra == -110)
sb.append("Media Player Error : "+extra);
else
sb.append("Unknown Media Player Error");
//sb.append(extra);
PreviewActivity.backClick = false;
showErrorDialog("Cannot play Audio", sb.toString());
return true;
@SuppressWarnings("deprecation")
void showErrorDialog(String title, String message)
try
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Icon to Dialog
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
// Setting Background color to Dialog
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int which)
// Write your code here to execute after dialog closed
dialog.dismiss();
finish();
onBackPressed();
);
// Showing Alert Message
if(this!= null && !this.isFinishing())
alertDialog.show();
catch(IllegalArgumentException Iae)
Iae.printStackTrace();
// handle the info and warning of the media player
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
//sb.append("Media Player Error: ");
if(Constants.DEBUG)Log.d("AudioStream", "Info : "+what+" "+extra);
switch (what)
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Media Error Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
//sb.append(" (" + what + ") ");
if(extra == -1004)
sb.append("Network interruption occured : "+extra);
else if(extra == -110)
sb.append("Media Player Error : "+extra);
else
sb.append("Unknown Media Player Error");
//sb.append(extra);
PreviewActivity.backClick = false;
showErrorDialog("Cannot play Audio", sb.toString());
return true;
class AudioStreamingAsyntask extends AsyncTask<String, Integer, Result>
ProgressDialog mProgressDialog;
@Override
protected void onPreExecute()
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(AudioStream.this);
mProgressDialog.setMessage("Loading...");
if(mProgressDialog != null)
mProgressDialog.show();
@Override
protected Result doInBackground(String... params)
// TODO Auto-generated method stub
String url = params[0];
setDataSource(url);
return null;
@Override
protected void onPostExecute(Result result)
// TODO Auto-generated method stub
super.onPostExecute(result);
mProgressDialog.dismiss();
mProgressDialog = null;
Thanks in Advance.
asked May 13 '14 at 5:58
sivasiva
155420
155420
Go to official docs for best explanation
– M D
May 13 '14 at 6:01
Thank for your comment, could u please give some example code depends on my code
– siva
May 13 '14 at 6:07
all the required code snippet available in that link.
– M D
May 13 '14 at 6:10
i don't know how to integrate those code into my code part, i getting some difficulties while integrating.So please bring some example or tutorials depends upon my code that would be helpful
– siva
May 14 '14 at 5:37
add a comment |
Go to official docs for best explanation
– M D
May 13 '14 at 6:01
Thank for your comment, could u please give some example code depends on my code
– siva
May 13 '14 at 6:07
all the required code snippet available in that link.
– M D
May 13 '14 at 6:10
i don't know how to integrate those code into my code part, i getting some difficulties while integrating.So please bring some example or tutorials depends upon my code that would be helpful
– siva
May 14 '14 at 5:37
Go to official docs for best explanation
– M D
May 13 '14 at 6:01
Go to official docs for best explanation
– M D
May 13 '14 at 6:01
Thank for your comment, could u please give some example code depends on my code
– siva
May 13 '14 at 6:07
Thank for your comment, could u please give some example code depends on my code
– siva
May 13 '14 at 6:07
all the required code snippet available in that link.
– M D
May 13 '14 at 6:10
all the required code snippet available in that link.
– M D
May 13 '14 at 6:10
i don't know how to integrate those code into my code part, i getting some difficulties while integrating.So please bring some example or tutorials depends upon my code that would be helpful
– siva
May 14 '14 at 5:37
i don't know how to integrate those code into my code part, i getting some difficulties while integrating.So please bring some example or tutorials depends upon my code that would be helpful
– siva
May 14 '14 at 5:37
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23623758%2fhow-to-add-the-service-for-my-custom-media-player-in-android%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f23623758%2fhow-to-add-the-service-for-my-custom-media-player-in-android%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Go to official docs for best explanation
– M D
May 13 '14 at 6:01
Thank for your comment, could u please give some example code depends on my code
– siva
May 13 '14 at 6:07
all the required code snippet available in that link.
– M D
May 13 '14 at 6:10
i don't know how to integrate those code into my code part, i getting some difficulties while integrating.So please bring some example or tutorials depends upon my code that would be helpful
– siva
May 14 '14 at 5:37