最近做了后台音频播放的功能,要求不同界面统一控制。其实后台音频播放比较多,但界面都大体相似,播放,暂停,快进,进度条之类,这种情况下,就可以将他封装成一个库,方便后期调用。
本demo通过service播放音频,然后通过发送广播来控制,各种状态已经做了封装,不需要开发者重新去编写。
MainActivity
public class MainActivity extends Activity {
public static final String URL_VOICE = "http://img.owspace.com/F_usw5969_1452853506.4724571.mp3";
private VoiceViewHolder mVoiceHolder;
private MediaServiceController mVoiceControl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initWidget();
setupListener();
loadData();
}
private void initView(){
}
private void initWidget(){
}
private void setupListener(){
findViewById(R.id.jump_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
jump2ArticlePage();
}
});
}
private void loadData(){
initVoiceMode();
}
private void initVoiceMode(){
View view = findViewById(R.id.voice_rl);
mVoiceHolder = new VoiceViewHolder(view);
mVoiceHolder.imgIv.setImageResource(R.mipmap.index);
mVoiceControl = new MediaServiceController(this, mVoiceHolder, URL_VOICE);
setupVoiceControlListener(mVoiceControl);
}
private void setupVoiceControlListener(MediaServiceController control) {
control.setOnMediaControlListener(new MediaServiceController.OnVioceControlProxy() {
@Override
public void onError(int code, String msg) {
CommonTools.showToast(MainActivity.this, msg);
}
@Override
public boolean onClickPlay() {
DebugTools.d("media2 video2 onClickPlay");
return true;
}
});
}
private void jump2ArticlePage(){
Intent intent = new Intent(this, NewsActivity.class);
if(mVoiceControl != null){
DebugTools.d("voice2 fragment mVoiceControl.getPlayState(): " + mVoiceControl.getPlayState());
intent.putExtra(NewsActivity.KEY_PLAY_STATE, mVoiceControl.getPlayState());
intent.putExtra(Constants.KEY_INTENT_IS_FROM_HOME, true);
}
startActivityForResult(intent, Constants.CODE_UPDATE_COMMENT_LIKE_COUNT);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Constants.CODE_UPDATE_COMMENT_LIKE_COUNT){
if(data == null){
return;
}
PlayState state = (PlayState)data.getSerializableExtra(NewsActivity.KEY_PLAY_STATE);
handledVoiceStateWhenActivityBack(state);
}
}
private void handledVoiceStateWhenActivityBack(PlayState state){
if(mVoiceControl != null){
if(mVoiceControl.getPlayState() != state){
mVoiceControl.showPlayState(state);
}
}
}
@Override
protected void onStart() {
registerMediaControlBroadcast();
super.onStart();
}
@Override
protected void onStop() {
unregisterMediaControlBroadcast();
super.onStop();
}
@Override
protected void onDestroy() {
if(mVoiceControl != null){
mVoiceControl.stop();
}
super.onDestroy();
}
class MediaControlBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent == null){
// DebugTools.d("voice2 home MediaControlBroadcast onReceive return-----------");
return;
}
if(mVoiceControl != null){
mVoiceControl.handleMediaBroadcastData(intent);
}
}
}
private MediaControlBroadcast mMediaControlBroadcast;
private void registerMediaControlBroadcast(){
if(mMediaControlBroadcast == null){
mMediaControlBroadcast = new MediaControlBroadcast();
}
IntentFilter filter = new IntentFilter();
filter.addAction(MediaServiceController.BRODCAST_ACTION_MEDIA_CONTROL);
registerReceiver(mMediaControlBroadcast, filter);
}
private void unregisterMediaControlBroadcast(){
if(mMediaControlBroadcast != null){
unregisterReceiver(mMediaControlBroadcast);
}
}
}
NewsActivity 第二个界面
public class NewsActivity extends Activity {
public static final String KEY_PLAY_STATE = "KEY_PLAY_STATE";
@Bind(R.id.webview)
public WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
initView();
initWidget();
setupListener();
loadData();
}
private void initView(){
ButterKnife.bind(this);
}
private void initWidget(){
initWebViewStorage(mWebView);
}
private void setupListener(){
setupWebViewListener();
}
private void loadData(){
initParams();
String url = "http://static.owspace.com/wap/291588.html";
loadWebviewUrl(url);
initVoiceMode();
}
private MediaServiceController.PlayState mPlayState;
protected void initParams(){
Intent intent = getIntent();
if(intent != null){
mPlayState = (MediaServiceController.PlayState)intent.getSerializableExtra(KEY_PLAY_STATE);
if(mPlayState == null){
mPlayState = PlayState.INIT;
}
}
}
protected void loadWebviewUrl(String url){
DebugTools.d("js2 discovery2 jump3 vote2 news2 current url: " + url);
if(!TextUtils.isEmpty(url)){
mWebView.loadUrl(url);
}
}
//------------voice------------------
private VoiceViewHolder mVoiceHolder;
private MediaServiceController mVoiceControl;
private void initVoiceMode(){
View view = findViewById(R.id.voice_rl);
mVoiceHolder = new VoiceViewHolder(view);
mVoiceHolder.imgIv.setImageResource(R.mipmap.index);
mVoiceControl = new MediaServiceController(this, mVoiceHolder, MainActivity.URL_VOICE);
setupVoiceControlListener(mVoiceControl);
mVoiceControl.showPlayState(mPlayState);
}
private void setupVoiceControlListener(MediaServiceController control){
control.setOnMediaControlListener(new MediaServiceController.OnVioceControlProxy() {
@Override
public void onError(int code, String msg) {
CommonTools.showToast(NewsActivity.this, msg);
}
@Override
public boolean onClickPlay() {
DebugTools.d("media2 video2 onClickPlay");
return true;
}
});
}
//-------------broadcast----------------
@Override
protected void onStart() {
registerMediaControlBroadcast();
super.onStart();
}
@Override
protected void onStop() {
unregisterMediaControlBroadcast();
super.onStop();
}
class MediaControlBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent == null){
// DebugTools.d("voice2 home MediaControlBroadcast onReceive return-----------");
return;
}
if(mVoiceControl != null){
mVoiceControl.handleMediaBroadcastData(intent);
}
}
}
private MediaControlBroadcast mMediaControlBroadcast;
private void registerMediaControlBroadcast(){
if(mMediaControlBroadcast == null){
mMediaControlBroadcast = new MediaControlBroadcast();
}
IntentFilter filter = new IntentFilter();
filter.addAction(MediaServiceController.BRODCAST_ACTION_MEDIA_CONTROL);
registerReceiver(mMediaControlBroadcast, filter);
}
private void unregisterMediaControlBroadcast(){
if(mMediaControlBroadcast != null){
unregisterReceiver(mMediaControlBroadcast);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
handleClickBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void handleClickBack() {
Intent data = new Intent();
if(mVoiceControl != null){
data.putExtra(KEY_PLAY_STATE, mVoiceControl.getPlayState());
}
setResult(200, data);
finish();
}
//-------------webview--------------
protected void initWebViewStorage(WebView webview){
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setAppCacheMaxSize(1024*1024*8);
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
webview.getSettings().setAllowFileAccess(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setDatabaseEnabled(true);
webview.getSettings().setDatabasePath(appCachePath);
}
protected void initWebViewSetting(WebView webview){
WebSettings webseting = webview.getSettings();
// webseting.setRenderPriority(RenderPriority.HIGH);
webseting.setJavaScriptEnabled(true);
// webseting.setPluginsEnabled(true);
webseting.setSupportZoom(true);
webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webseting.setUseWideViewPort(true);
webseting.setLoadWithOverviewMode(true);
initWebViewStorage(webview);
}
protected void setupWebViewListener() {
mWebView.setWebViewClient(new WebViewClient() {
});
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress){
super.onProgressChanged(view, newProgress);
}
});
}
@Override
protected void onDestroy() {
ButterKnife.unbind(this);
super.onDestroy();
}
}
MediaPlayService 播放音频的Service
public class MediaPlayService extends Service implements OnBufferingUpdateListener,
OnCompletionListener, MediaPlayer.OnPreparedListener {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
DebugTools.d("voice2 service oncreate");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
DebugTools.d("voice2 service onStart intent null: " + (intent == null));
if(intent != null){
int command = intent.getIntExtra(MediaServiceController.KEY_MEDIA_CONTROL_COMMAND, 0);
handleMediaControlAction(command, intent);
}
}
private void handleMediaControlAction(int command, Intent intent){
DebugTools.d("comment2 handleMediaControlAction command: " + command);
if(command == MediaServiceController.COMMAND_PLAY){
String url = intent.getStringExtra(MediaServiceController.KEY_URL);
DebugTools.d("comment2 handleMediaControlAction url: " + url);
handleClickPlay(url);
}else if(command == MediaServiceController.COMMAND_RESUME){
handleClickResume();
}else if(command == MediaServiceController.COMMAND_PAUSE){
handleClickPause();
}else if(command == MediaServiceController.COMMAND_SEEK_TO){
boolean isDraged = intent.getBooleanExtra(MediaServiceController.KEY_BOOLEAN, false);
float rate = intent.getFloatExtra(MediaServiceController.KEY_FLOAT, 0);
int progress = (int)(mPlayer.getDuration() * rate);
handleSeekTo(progress, isDraged);
}else if(command == MediaServiceController.COMMAND_START_SEEK){
removeUpdateTimeMsg();
}else if(command == MediaServiceController.COMMAND_DESTROY){
stopAndDestory();
}
}
private void handleSeekTo(int progress, boolean isDraged){
mPlayer.seekTo(progress);
if(isDraged){
sendUpdateTimeMsg();
}
}
public MediaPlayer mPlayer;
private void createMediaPlayer(){
if(mPlayer != null){
return;
}
try {
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setOnBufferingUpdateListener(this);
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
} catch (Exception e) {
Log.e("mPlayer", "error", e);
}
}
private void handleClickPlay(String url){
if(TextUtils.isEmpty(url)){
return;
}
url = url.trim();
createMediaPlayer();
playUrl(url);
// sendUpdateTimeMsg();
}
private void handleClickPause(){
mPlayer.pause();
removeUpdateTimeMsg();
}
private void handleClickResume(){
sendUpdateTimeMsg();
mPlayer.start();
}
private void sendMediaStateUpdateBrodcast(int command){
Intent intent = new Intent(MediaServiceController.BRODCAST_ACTION_MEDIA_CONTROL);
intent.putExtra(MediaServiceController.KEY_MSG_UPDATE_MEDIA_STATE, command);
sendBroadcast(intent);
}
private void sendUpdateMediaTimeBrodcast(int curTime, int totalTime){
int[] arr = {curTime, totalTime};
Intent intent = new Intent(MediaServiceController.BRODCAST_ACTION_MEDIA_CONTROL);
intent.putExtra(MediaServiceController.KEY_MSG_UPDATE_MEDIA_STATE, MediaServiceController.MSG_UPDATE_STATE_TIME);
intent.putExtra(MediaServiceController.KEY_INT_ARR, arr);
sendBroadcast(intent);
}
private static final int MSG_UPDATE_TIME = 101;
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what){
case MSG_UPDATE_TIME:
if (mPlayer != null && mPlayer.isPlaying()) {
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
sendUpdateMediaTimeBrodcast(position, duration);
if(position < duration){
sendUpdateTimeMsg();
}
}
break;
}
};
};
private void sendUpdateTimeMsg(){
if(mHandler != null){
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, 1000);
}
}
private void removeUpdateTimeMsg(){
if(mHandler != null){
mHandler.removeMessages(MSG_UPDATE_TIME);
}
}
// *****************************************************
public void playUrl(String videoUrl) {
try {
String path = getLocalOrOnlineUrl(videoUrl);
mPlayer.reset();
mPlayer.setDataSource(path);
mPlayer.prepare();// prepare之后自动播放
// mPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private String getLocalOrOnlineUrl(String url){
String path = CommonTools.getMediaSavePathByUrl(url);
File file = new File(path);
boolean isExist = file != null && file.exists();
DebugTools.d("file3 voice2 service playUrl url: " + url + " path: " + path + " isExist: " + isExist);
if(isExist){
return path;
}
return url;
}
private void stopAndDestory() {
DebugTools.d("voice2 service stopAndDestory");
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
removeUpdateTimeMsg();
mHandler = null;
stopSelf();
}
/**
* 通过onPrepared播放
*/
@Override
public void onPrepared(MediaPlayer arg0) {
arg0.start();
DebugTools.d("voice2 voice onPrepared");
sendUpdateTimeMsg();
// showPlayingState(mHolder);
sendMediaStateUpdateBrodcast(MediaServiceController.MSG_UPDATE_STATE_PLAYING);
// mHolder.totalTimeTv.setText(getShowTimeByMs(arg0.getDuration()));
// sendUpdateMediaTimeBrodcast(0, arg0.getDuration());
}
@Override
public void onCompletion(MediaPlayer arg0) {
DebugTools.d("media2 voice onCompletion");
// showInitStateState(mHolder);
sendMediaStateUpdateBrodcast(MediaServiceController.MSG_UPDATE_STATE_INIT);
if(mHandler != null){
mHandler.removeMessages(MSG_UPDATE_TIME);
}
}
@Override
public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {
}
}
MediaServiceController 控制器
public class MediaServiceController {
public static final String KEY_FLOAT = "KEY_FLOAT";
public static final String KEY_BOOLEAN = "KEY_BOOLEAN";
public static final String KEY_INT_ARR = "KEY_INT_ARR";
public static final String KEY_URL = "KEY_URL";
public static final String BRODCAST_ACTION_MEDIA_CONTROL = "BRODCAST_ACTION_MEDIA_CONTROL";
public static final String KEY_MSG_UPDATE_MEDIA_STATE = "KEY_MSG_UPDATE_MEDIA_STATE";
public static final int MSG_UPDATE_STATE_INIT = 100;
public static final int MSG_UPDATE_STATE_PREPARE = 101;
public static final int MSG_UPDATE_STATE_PAUSE = 102;
public static final int MSG_UPDATE_STATE_PLAYING = 103;
public static final int MSG_UPDATE_STATE_TIME = 104;
public static final String KEY_MEDIA_CONTROL_COMMAND = "KEY_MEDIA_CONTROL_COMMAND";
public static final int COMMAND_PLAY = 105;
public static final int COMMAND_PAUSE = 106;
public static final int COMMAND_RESUME = 107;
public static final int COMMAND_DESTROY = 108;
public static final int COMMAND_SEEK_TO = 109;
public static final int COMMAND_START_SEEK = 110;
private SeekBar sBar;
private VoiceViewHolder mHolder;
private String mUrl;
private Context mContext;
public MediaServiceController(Context context, VoiceViewHolder holder, String url) {
mContext = context;
this.sBar = holder.seekBar;
mHolder = holder;
mUrl = url;
setupListener();
showInitStateState(holder);
}
private void setupListener(){
setupSeekBarListener(sBar);
setControlBarListener(mHolder);
}
private void setupSeekBarListener(final SeekBar seekBar){
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
float rate;
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(seekBar != null && seekBar.isPressed()){
rate = progress * 1.0f / seekBar.getMax();
// handleUpdateTime((int)(rate * mTotalTime), mTotalTime);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
DebugTools.d("voice2 seekbar onStartTrackingTouch");
sendMediaControlCommand(COMMAND_START_SEEK);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
DebugTools.d("voice2 seekbar onStopTrackingTouch");
// seekTo()的参数是相对与影片时间的数字,而不是与seekBar.getMax()相对的数字
handleUpdateTime((int)(rate * mTotalTime), mTotalTime);
sendSeekToCommand(rate, true);
}
});
}
private void sendSeekToCommand(float rate, boolean isDrag){
Intent intent = new Intent(mContext, MediaPlayService.class);
intent.putExtra(KEY_MEDIA_CONTROL_COMMAND, COMMAND_SEEK_TO);
intent.putExtra(KEY_FLOAT, rate);
intent.putExtra(KEY_BOOLEAN, isDrag);
mContext.startService(intent);
}
private void sendMediaControlCommand(int command, String url){
Intent intent = new Intent(mContext, MediaPlayService.class);
intent.putExtra(KEY_MEDIA_CONTROL_COMMAND, command);
intent.putExtra(KEY_URL, url);
mContext.startService(intent);
DebugTools.d("voice2 sendMediaControlCommand command: " + command + " url: " + url);
}
private void sendMediaControlCommand(int command){
DebugTools.d("voice2 sendMediaControlCommand command: " + command);
Intent intent = new Intent(mContext, MediaPlayService.class);
intent.putExtra(KEY_MEDIA_CONTROL_COMMAND, command);
mContext.startService(intent);
}
private PlayState mPlayState = PlayState.INIT;
private void setControlBarListener(final VoiceViewHolder holder){
holder.playSymbolIv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
handleClickPlay(holder);
}
});
holder.playPauseIb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
handleClickPlay(holder);
}
});
holder.imgIv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mPlayState == PlayState.INIT){
handleClickPlay(holder);
}
}
});
holder.speedIb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
handleSpeedDecelerate(DELTA);
}
});
holder.decelerateIb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
handleSpeedDecelerate(-DELTA);
}
});
}
private int mCurrentTime = 0;
private int mTotalTime = 0;
private static final int DELTA = 10 * 1000;
private void handleSpeedDecelerate(int delta){
// int position = mPlayer.getCurrentPosition();
// int duration = mPlayer.getDuration();
int position = mCurrentTime;
int duration = mTotalTime;
DebugTools.d("voice2 duration: " + duration + " position: " + position + " delta: " + delta);
if(duration <= 0){
return;
}
position += delta;
if(position < 0){
position = 0;
}
if(position > duration){
position = duration;
}
DebugTools.d("voice2 duration: " + duration + " position: " + position + " delta: " + delta + "--------------");
float rate = position * 1.0f / duration;
handleUpdateTime(position, duration);
sendSeekToCommand(rate, false);
}
public void handleMediaBroadcastData(Intent intent){
if(intent == null){
return;
}
int action = intent.getIntExtra(KEY_MSG_UPDATE_MEDIA_STATE, 0);
handleUpdateState(action, intent);
}
public void mockClickStartPlay(){
mUrl = mUrl.trim();
showPreparePlayState(mHolder);
sendMediaControlCommand(COMMAND_PLAY, mUrl);
}
private void handleClickPlay(final VoiceViewHolder holder){
DebugTools.d("voice2 handleClickPlay mPlayState: " + mPlayState);
if(mPlayState == PlayState.INIT){
DebugTools.d("voice2 handleClickPlay mUrl: " + mUrl);
if(TextUtils.isEmpty(mUrl)){
if(mOnVideoControlListener != null){
mOnVideoControlListener.onError(0, "地址为空");
}
return;
}
if(mOnVideoControlListener != null && mOnVideoControlListener.onClickPlay()){
mockClickStartPlay();
}
DebugTools.d("media2 handleClickPlay mUrl: " + mUrl);
}else if(mPlayState == PlayState.PLAYING){
sendMediaControlCommand(COMMAND_PAUSE);
showPauseState(holder);
}else if(mPlayState == PlayState.PAUSE){
sendMediaControlCommand(COMMAND_RESUME);
showPlayingState(holder);
}
}
public void showPlayState(PlayState state){
if(state == null){
state = PlayState.INIT;
}
if(mPlayState == state){
return;
}
mPlayState = state;
if(mPlayState == PlayState.INIT){
showInitStateState(mHolder);
}else if(mPlayState == PlayState.PLAYING){
showPlayingState(mHolder);
}else if(mPlayState == PlayState.PAUSE){
showPauseState(mHolder);
}
}
private void showPlayingState(VoiceViewHolder holder){
mPlayState = PlayState.PLAYING;
holder.playPauseIb.setImageResource(R.mipmap.library_voice_mediacontroller_pause);
updateViewVisibleState(holder.mediaControl, View.VISIBLE);
updateViewVisibleState(holder.playSymbolIv, View.INVISIBLE);
updateViewVisibleState(holder.pb, View.INVISIBLE);
if(mOnVideoControlListener != null){
mOnVideoControlListener.onClickResume();
}
}
private void showPauseState(VoiceViewHolder holder){
mPlayState = PlayState.PAUSE;
holder.playPauseIb.setImageResource(R.mipmap.library_voice_mediacontroller_play);
updateViewVisibleState(holder.mediaControl, View.VISIBLE);
updateViewVisibleState(holder.playSymbolIv, View.INVISIBLE);
updateViewVisibleState(holder.pb, View.INVISIBLE);
if(mOnVideoControlListener != null){
mOnVideoControlListener.onPrepared();
}
}
private void showInitStateState(VoiceViewHolder holder){
mPlayState = PlayState.INIT;
holder.imgIv.setVisibility(View.VISIBLE);
holder.seekBar.setProgress(0);
holder.playPauseIb.setImageResource(R.mipmap.library_video_mediacontroller_play);
holder.curTimeTv.setText("00:00");
updateViewVisibleState(holder.mediaControl, View.INVISIBLE);
updateViewVisibleState(holder.playSymbolIv, View.VISIBLE);
updateViewVisibleState(holder.pb, View.INVISIBLE);
}
private void showPreparePlayState(VoiceViewHolder holder){
mPlayState = PlayState.PREPARE;
updateViewVisibleState(holder.pb, View.VISIBLE);
updateViewVisibleState(holder.playSymbolIv, View.INVISIBLE);
}
private void updateViewVisibleState(View view, int visibleState){
if(view.getVisibility() != visibleState){
view.setVisibility(visibleState);
}
}
public void pause() {
if(mHolder == null){
return;
}
if(mPlayState == PlayState.PLAYING){
sendMediaControlCommand(COMMAND_PAUSE);
showPauseState(mHolder);
}
}
public PlayState getPlayState(){
return mPlayState;
}
public void stop() {
if(mHolder != null){
showInitStateState(mHolder);
}
sendMediaControlCommand(COMMAND_DESTROY);
}
private void handleUpdateState(int state, Intent intent){
DebugTools.d("voice2 handleUpdateState state: " + state);
if(state == MSG_UPDATE_STATE_INIT){
showInitStateState(mHolder);
}else if(state == MSG_UPDATE_STATE_PREPARE){
showPreparePlayState(mHolder);
}else if(state == MSG_UPDATE_STATE_PLAYING){
showPlayingState(mHolder);
}else if(state == MSG_UPDATE_STATE_PAUSE){
showPauseState(mHolder);
}else if(state == MSG_UPDATE_STATE_TIME){
int[] timeArr = intent.getIntArrayExtra(KEY_INT_ARR);
if(timeArr != null && timeArr.length == 2){
handleUpdateTime(timeArr[0], timeArr[1]);
}
}
}
private void handleUpdateTime(int position, int duration){
mCurrentTime = position;
mTotalTime = duration;
if (duration > 0) {
long pos = sBar.getMax() * position / duration;
sBar.setProgress((int) pos);
}
mHolder.curTimeTv.setText(getShowTimeByMs(position));
mHolder.totalTimeTv.setText("-" + getShowTimeByMs(duration - position));
}
public enum PlayState{
INIT, PREPARE, PLAYING, PAUSE
}
public static class VoiceViewHolder{
public RelativeLayout mediaControl;
public ImageView playPauseIb;
public SeekBar seekBar;
public ImageView imgIv;
public ImageView playSymbolIv;
public TextView curTimeTv;
public TextView totalTimeTv;
public ProgressBar pb;
public ImageButton speedIb;
public ImageButton decelerateIb;
public VoiceViewHolder(View convertView){
mediaControl = (RelativeLayout) convertView.findViewById(R.id.voice_control_rl);
playPauseIb = (ImageView) convertView.findViewById(R.id.mediacontroller_play_pause);
seekBar = (SeekBar) convertView.findViewById(R.id.mediacontroller_seekbar);
imgIv = (ImageView) convertView.findViewById(R.id.voice_image_iv);
playSymbolIv = (ImageView) convertView.findViewById(R.id.voice_play_symbol_iv);
curTimeTv = (TextView)convertView.findViewById(R.id.mediacontroller_time_current);
totalTimeTv = (TextView)convertView.findViewById(R.id.mediacontroller_time_total);
pb = (ProgressBar) convertView.findViewById(R.id.loading_pb);
speedIb = (ImageButton) convertView.findViewById(R.id.mediacontroller_speed);
decelerateIb = (ImageButton) convertView.findViewById(R.id.mediacontroller_decelerate);
}
}
private OnVioceControlListener mOnVideoControlListener;
public void setOnMediaControlListener(OnVioceControlListener listener){
mOnVideoControlListener = listener;
}
public interface OnVioceControlListener{
/**
* @return true,直接播放;false,不播放客户端处理(播放时,使用的是流量的情况,这是可以弹个提示框之类的)
*/
public boolean onClickPlay();
public void onPrepared();
public void onClickResume();
public void onClickPause();
public void onCompletion();
public void onError(int code, String msg);
}
public static class OnVioceControlProxy implements OnVioceControlListener{
@Override
public boolean onClickPlay() {
return true;
}
@Override
public void onPrepared() {
}
@Override
public void onClickResume() {
}
@Override
public void onClickPause() {
}
@Override
public void onCompletion() {
}
@Override
public void onError(int code, String msg) {
}
}
private String getShowTimeByMs(int time){
time = time / 1000;
int minute = time / 60;
int second = time % 60;
StringBuffer buffer = new StringBuffer();
if(minute < 10){
buffer.append("0" + minute);
}else{
buffer.append(minute);
}
buffer.append(":");
if(second < 10){
buffer.append("0" + second);
}else{
buffer.append(second);
}
return buffer.toString();
}
}