Android仿酷狗音樂SeekBar——控制篇
需求:
- 根據(jù)后臺播放狀態(tài)調(diào)整SeekBar的滑塊位置;
- 反饋用戶的滑動滑塊事件;
分析:
一般我們的視頻或者音樂播放是由后臺Service播放的,而SeekBar是在前臺Activity或者Fragment里,所以根據(jù)播放狀態(tài)我們調(diào)整SeekBar滑塊可以讓Service主動發(fā)送數(shù)據(jù)給前臺,而反饋用戶滑塊事件,直接在前臺獲得Service實(shí)例,然后操作相關(guān)控制媒體播放的方法即可。
1. 后臺Service給前臺發(fā)送媒體播放進(jìn)度
這里我們使用Timer新建一個(gè)Timertask,間隔執(zhí)行,然后在暫?;蛘呓Y(jié)束后停止發(fā)送
public void SeedPlayMsg(){
if(timer == null) {
Log.d(TAG, "創(chuàng)建timer對象");
timer = new Timer();//timer就是開啟子線程執(zhí)行任務(wù),與純粹的子線城不同的是可以控制子線城執(zhí)行的時(shí)間,
}
timer.schedule(new TimerTask() {
@Override
public void run() {
//獲取歌曲當(dāng)前播放進(jìn)度
int currentPosition = player.getCurrentPosition();
Message msg = AudioPlayActivity.handler.obtainMessage();
Bundle bundle = new Bundle();
msg.what = 1;
bundle.putInt("currentPosition", currentPosition);
bundle.putBoolean("isPlayComplete", false);
if (player.isPlaying()) {
//把進(jìn)度封裝至消息對象中
msg.setData(bundle);
AudioPlayActivity.handler.sendMessage(msg);
}
else {
if (isPlayComplete) {
bundle.putBoolean("isPlayComplete", true);
Log.d(TAG, "發(fā)送消息給主線程,播放已結(jié)束");
}
else{
bundle.putBoolean("isPlayComplete", false);
}
msg.setData(bundle);
AudioPlayActivity.handler.sendMessage(msg);
Log.d(TAG, "結(jié)束TimeTask");
timer.cancel();
}
}
//開始計(jì)時(shí)任務(wù)后的5毫秒后第一次執(zhí)行run方法,以后每500毫秒執(zhí)行一次
}, 200, 500);
}
這里有個(gè)很重要的細(xì)節(jié),就是發(fā)送播放結(jié)束的消息,一般我們認(rèn)為當(dāng)發(fā)送的位置等于媒體的長度時(shí),我們就認(rèn)為是結(jié)束了,可事實(shí)上不是這樣的,因?yàn)镸ediaPlayer對象的getCurrentPosition()方法在媒體播放結(jié)束后獲取到的值也與獲取時(shí)常的方法getDuration()得到的值不一致,總是要小,而且還不固定。
所以為了精確播放是否完成,我們還是由原生接口監(jiān)聽去判斷播放是否完成
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.d(TAG,"播放結(jié)束");
isPlayComplete = true;
}
});
前臺Activity或者Fragment接收當(dāng)前媒體播放進(jìn)度信息并,調(diào)整SeekBar進(jìn)度
static Handler handler = new Handler(){//handler是谷歌說明的定義成靜態(tài)的,
public void handleMessage(Message msg) {
switch (msg.what) {
default:
case 1:
Bundle bundle = msg.getData();
boolean isPlayComplete = bundle.getBoolean("isPlayComplete");
int currentPosition = bundle.getInt("currentPosition");
//根據(jù)當(dāng)前位置判斷錄音是否結(jié)束,結(jié)束后更新UI
if (isPlayComplete) {
seekBar.setProgress(seekBar.getMax());
}
else {
if (!isUserPressThumb) seekBar.setProgress(currentPosition);
}
break;
case 2:
Bundle bundle2 = msg.getData();
int duration = bundle2.getInt("duration");
seekBar.setMax(duration);
break;
}
}
};
這里有個(gè)很重要的細(xì)節(jié),和容易忽略,就是判斷用戶是否在拖動進(jìn)度條,如果用戶在拖動中,那么就執(zhí)行setProgress;這個(gè)如果不做判斷,在一些手機(jī)上會出現(xiàn)用戶在媒體播放時(shí)拖動進(jìn)度條還沒放開,滑塊跑到setProgress設(shè)置的位置上,然后馬上又跑回用戶拖動的位置上,很坑爹。
所以這里我們加一個(gè)判斷if (!isUserPressThumb)
前面我們說了getCurrentPosition()方法返回的數(shù)值(單位是毫秒)永遠(yuǎn)比getDuration()要小,而我們進(jìn)度條的最大值是用getDuration()方法獲取的值設(shè)置的,所以為了一致,我們要在接收到播放完成的消息后,將SeekBar調(diào)到最大值
if (isPlayComplete) { seekBar.setProgress(seekBar.getMax()); }
在媒體準(zhǔn)備好后,我們要發(fā)送媒體的長度給前臺,使用這個(gè)設(shè)置前臺SeekBar的最大長度,當(dāng)然,你也可以將SeekBar最大長度設(shè)置為某個(gè)值(默認(rèn)100),然后跟進(jìn)媒體播放進(jìn)度進(jìn)行等比換算,在這里我們不換算了,直接將媒體的長度設(shè)置為SeekBar的長度,簡單易懂。
public void SeedPlayDuration() {
Message msg = AudioPlayActivity.handler.obtainMessage();
msg.what = 2;
//把進(jìn)度封裝至消息對象中
Bundle bundle = new Bundle();
bundle.putInt("duration", getDuration());
msg.setData(bundle);
AudioPlayActivity.handler.sendMessage(msg);
}
結(jié)合上面的前臺Handler接收到消息,設(shè)置SeekBar最大長度。
(為保證后續(xù)開始播放后發(fā)送進(jìn)度調(diào)整SeekBar不會超出SeekBar原來的最大長度,所以前一篇的定時(shí)發(fā)送位置的任務(wù),我們是延遲200ms進(jìn)行的)
2. 反饋用戶的滑動滑塊事件
由前臺監(jiān)聽調(diào)用后臺Service方法完成
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
Seekbar_slider_time.setText(updateCurrentTimeText(progress));
}
tx_currentTime.setText(updateCurrentTimeText(progress));
if(progress == seekBar.getMax()){
pauseIcon.setLayoutParams(miss);
playIcon.setLayoutParams(show);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.d(TAG,"onStartTrackingTouch");
isUserPressThumb = true;
Seekbar_slider_time.setVisibility(View.VISIBLE);
//設(shè)置seekbarThumb相對位置可大于進(jìn)度條15,保證thumb在變成40dp直徑后可以滑動到進(jìn)度條最末尾
seekBar.setThumbOffset(15);
seekBar.setThumb(Thumb_pressed);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.d(TAG,"onStopTrackingTouch");
mi.seekTo(seekBar.getProgress());
seekBar.setThumbOffset(0);
seekBar.setThumb(Thumb_normal);
Seekbar_slider_time.setVisibility(View.INVISIBLE);
if(!(seekBar.getProgress() == seekBar.getMax())) isUserPressThumb = false;
}
});
主要是在onStopTrackingTouch中,也就是用戶點(diǎn)擊或滑動滑塊完成階段執(zhí)行
mi.seekTo(seekBar.getProgress());——這里mi是獲取到的Service對象,seekTo是設(shè)置當(dāng)前播放位置的方法。
在onStartTrackingTouch中,也就是用戶開始點(diǎn)擊或者滑動滑塊開始階段,我們設(shè)置
isUserPressThumb = true;
以配合前面Handler中控制SeekBar位置的代碼,原因我前面已經(jīng)說了。
最后在onStopTrackingTouch中,設(shè)置
if(!(seekBar.getProgress() == seekBar.getMax())) isUserPressThumb = false;(如果沒有拖動到最后)
至于在onProgressChanged中,用戶點(diǎn)擊或者拖動滑塊中
if(fromUser){
Seekbar_slider_time.setText(updateCurrentTimeText(progress));
}
tx_currentTime.setText(updateCurrentTimeText(progress));
if(progress == seekBar.getMax()){
pauseIcon.setLayoutParams(miss);
playIcon.setLayoutParams(show);
}
需要注意的是boolean fromUser這個(gè)參數(shù),為true時(shí),表示是用戶改變的滑塊位置,false時(shí),是系統(tǒng)改變的,也就是我們前面Handler中進(jìn)行的改變;
如果是用戶拖動,我們相應(yīng)的在滑塊上面給用戶提示當(dāng)前到什么位置了
Seekbar_slider_time.setText(updateCurrentTimeText(progress));
當(dāng)然,這個(gè)控件平時(shí)是隱藏的,所以點(diǎn)擊開始時(shí)onStartTrackingTouch,我們需要顯示它
Seekbar_slider_time.setVisibility(View.VISIBLE);
拖動或點(diǎn)擊結(jié)束后onStopTrackingTouch,我們由隱藏它
Seekbar_slider_time.setVisibility(View.INVISIBLE);
在onProgressChanged我們設(shè)置顯示媒體的位置,代表播放到哪里了,或者即將播放到哪里了
tx_currentTime.setText(updateCurrentTimeText(progress));
另外當(dāng)滑塊滑動到最后了以后(由前面Handler接收到播放完成后設(shè)置的,也可能是用戶自己拖動到了最后)
我們需要變換播放或者暫停按鈕
if(progress == seekBar.getMax())
{
pauseIcon.setLayoutParams(miss);
playIcon.setLayoutParams(show);
}
附上毫秒裝換為時(shí)間格式hh:mm:ss的方法
public String updateCurrentTimeText(int currentPosition){
try {
int time= currentPosition/1000;
if (time >= 3600) {
int hour = time/3600;
int minute = (time/60) % 60;
int second = time % 60;
String Time = String.format(Locale.getDefault(),"%02d:%02d:%02d", hour, minute, second);
//tx_currentTime.setText(currentTime);
return Time;
}
else{
int minute = time/60;
int second = time % 60;
String Time = String.format(Locale.getDefault(),"%02d:%02d", minute, second);
//tx_currentTime.setText(currentTime);
return Time;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
};
項(xiàng)目地址https://github.com/magic5650/Recoderapp