我已经完成了自定义媒体播放器,用于从服务器传输音频文件,但我不知道如何将后台服务添加到此媒体播放器,并且喜欢在通知栏中添加我们可以控制和关闭音频球员本身。请告诉我任何人如何为自定义流媒体播放服务 - 音频播放器。
我的代码部分:
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;
}
}
}
先谢谢。