MusicProgressBar

public static String getDate(Long time){
  
  SimpleDateFormat sim = new SimpleDateFormat("mm:ss");
  Log.i("INFO", sim.format(time)+"time");
  return sim.format(time);
 }
     <SeekBar
                android:id="@+id/sb"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingTop="3dp"
                android:progressDrawable="@drawable/seek_bg"
                android:thumb="@drawable/icon_mytrack"
                android:thumbOffset="3dp" />
 
package com.hefen.activity.mp3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.hefen.adapter.mp3.MusicAdapter;
import com.hefen.application.mp3.MyApplication;
import com.hefen.entity.mp3.Mp3Info;
import com.hefen.entity.mp3.MusicInfo;
import com.hefen.lrc.mp3.LrcProcessor;
import com.hefen.service.mp3.MyService;
import com.hefen.util.mp3.GetMusicData;

public class HostOneList extends Activity implements OnTouchListener,
        OnClickListener {
    TextView lrcTextView = null;// 显示歌词
    ListView listView;
    MusicAdapter adapter;
    Uri uri;
    ImageButton ib_stop;
    SeekBar sb;// 进度条
    HorizontalScrollView hsv;
    //时间
    TextView tv_zou,tv_all;
    LinearLayout ll1, ll2, ll3;
    int width, heigth;
    TextView tv_name,tv_person;
    ImageButton play, stop, next, back, restart;
    // 音乐是否播放
    boolean isPause = false;
    int position = 0;
    List<MusicInfo> lists = null;
    MusicInfo info;
    Mp3Info lrc_info;
    String lrcName;
    //boolean isNext = true;// 默认顺序
    //
    MyApplication application;
    MyService myService;
    //
    public static final int SEEKBAR = 222;
    //
    private UpdateTimeCallback updateTimeCallback = null;
    private long begin = 3;
    private long nextTimeMill = 0;
    private long currentTimeMill = 0;
    private String message = null;
    private ArrayList<Queue> queues = null;
    long timeprogress;
    //
    Button bt_showlrc;
    Handler handlerLrc=new Handler();
    Handler handlerSeekBar = new Handler();
    int start;
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            /*
             * System.out.println("myService.player.getCurrentPosition()" +
             * myService.player.getCurrentPosition());
             */
            // 拖延发送
            handlerSeekBar.postDelayed(runnable, 1000);//没一秒钟执行一次
            start=myService.player.getCurrentPosition();//得到播放的位置
            sb.setProgress(myService.player.getCurrentPosition());//设置进度条的位置
            timeprogress=myService.player.getCurrentPosition();//时间的多少
            //时间的走动
            tv_zou.setText(GetMusicData.getDate(timeprogress));
            //总的时间
            tv_all.setText(GetMusicData.getDate(lists.get(position).getTime()));//总共用的时间
            
                
        
        }
    };
    
    /**
     * 根据歌曲名字得到歌词
     * @return 
     */
public String getLrc(int positon2){
    String song=lists.get(positon2).getName();
    
    String lrc=song.substring(0,song.indexOf("."))+".lrc";
    
    Log.i("INFO-lrc",lrc);
        
    return lrc;
}
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hostonelist);
        // 按钮
        initViewButton();
        initView2();
        lists = GetMusicData.getMusicData(this);
        // 从application那里拿到service
        application = (MyApplication) this.getApplication();
        myService = application.getMyService();
        Log.i("INFO", position + "position");
        Log.i("INFO", myService + "myService");

        handler.post(runnable); // 获取播放音乐的最大值,设置给seekbar刻度最大值
        sb.setMax(myService.player.getDuration());
        tv_zou.setText("");
        int getP = this.getIntent().getIntExtra("position", 0);
        position = getP;
        
        Log.i("INFO", position + "改变的值");
        lrcName=getLrc(position);
        
    
        lrcTextView = (TextView) this.findViewById(R.id.lrcTextView);
        if (!myService.player.isPlaying()) {
            sb.setProgress(0);
        }
        actoNext(true);//默认是顺序播放
        
        
        /*//歌名    
        tv_person.setText(lists.get(position).getSinger()+"");
        //人名
        tv_name.setText(lists.get(position).getName()+"");*/
        
        xunhuan();
    }
    
    public void xunhuan(){
        for (MusicInfo info : lists) {
            Log.i("list", info.toString());
        }
    }
    
    //根据歌词文件的名字,来读取歌词文件中的信息
    private void prepareLrc(String src){
        try {
            InputStream inputStream = new FileInputStream(src);
            LrcProcessor lrcProcessor = new LrcProcessor();
            queues = lrcProcessor.process(inputStream);
            //创建一个UpdateTimeCallback对象
            updateTimeCallback = new UpdateTimeCallback(queues);
            begin = 0 ;//
            currentTimeMill = 0 ;
            nextTimeMill = 0 ;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    class UpdateTimeCallback implements Runnable{
        Queue<?> times = null;
        Queue<?> messages = null;
        public UpdateTimeCallback(ArrayList<Queue> queues) {
            //从ArrayList当中取出相应的对象对象
            times = queues.get(0);
            messages = queues.get(1);
        }
        @Override
        public void run() {
            //计算偏移量,也就是说从开始播放MP3到现在为止,共消耗了多少时间,以毫秒为单位
            long offset = System.currentTimeMillis() - begin;
            if(currentTimeMill == 0){
                nextTimeMill = (Long)times.poll();
                message = (String)messages.poll();
            }
            if(offset >= nextTimeMill){
                lrcTextView.setText(message);
                message = (String)messages.poll();
                nextTimeMill = (Long)times.poll();
            }
            currentTimeMill = currentTimeMill + 10;
            handler.postDelayed(updateTimeCallback, 10);
        }    
    }
    //歌曲循环
    public void actoNext(boolean isNext2) {
        final boolean next=isNext2;
        Log.i("INFO--", "next"+next);
        myService.player.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (next == false) {// 单曲循环
                    try {
                        myService.playMusic(lists.get(position).getUrl());
                        handler.post(runnable); // 获取播放音乐的最大值,设置给seekbar刻度最大值
                        sb.setMax(myService.player.getDuration());
                    
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {//顺序播放
                    if (position == lists.size() - 1) {
                        position = 0;
                    } else {
                        position = position + 1;
                    }
                    try {
                        myService.playMusic(lists.get(position).getUrl());
                        handler.post(runnable); // 获取播放音乐的最大值,设置给seekbar刻度最大值
                        sb.setMax(myService.player.getDuration());
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.audio_player_play:
            isPause = !isPause;
            if (isPause && myService.player.isPlaying()) {// 如果是暂停的话
                // play.setBackgroundResource(R.drawable.apollo_holo_dark_play);
                myService.pauseMusic();
            } else {
                // play.setBackgroundResource(R.drawable.apollo_holo_dark_pause);
                myService.continueMusic();
            }
            break;
        case R.id.audio_player_next:
            if (position == lists.size() - 1) {
                position = 0;
            } else {
                position = position + 1;
            }
            Log.i("position", position + "-->position");
            String url = lists.get(position).getUrl();
            try {
                myService.playMusic(url);
                handler.post(runnable); // 获取播放音乐的最大值,设置给seekbar刻度最大值
                sb.setMax(myService.player.getDuration());
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            break;
        case R.id.audio_player_prev:
            if (position == 0) {
                position = lists.size() - 1;
            } else {
                position = position - 1;
            }
            String url2 = lists.get(position).getUrl();
            Log.i("position", position + "-->position");
            try {
                myService.playMusic(url2);
                handler.post(runnable); // 获取播放音乐的最大值,设置给seekbar刻度最大值
                sb.setMax(myService.player.getDuration());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        case R.id.audio_player_repeat:
            //重新开始
            try {
                myService.playMusic(lists.get(position).getUrl());
                handler.post(runnable); // 获取播放音乐的最大值,设置给seekbar刻度最大值
                sb.setMax(myService.player.getDuration());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
        case R.id.audio_player_shuffle:
            // 点击了之后顺序播放
        
            break;
        default:
            break;
        }
        ;

    }

    private void initViewButton() {
        tv_name=(TextView) findViewById(R.id.tv_name);
        tv_person=(TextView) findViewById(R.id.tv_person);
        play = (ImageButton) findViewById(R.id.audio_player_play);
        next = (ImageButton) findViewById(R.id.audio_player_next);
        back = (ImageButton) findViewById(R.id.audio_player_prev);
        restart = (ImageButton) findViewById(R.id.audio_player_repeat);
        bt_showlrc=(Button) findViewById(R.id.bt_showlrc);
        
        play.setOnClickListener(this);
        next.setOnClickListener(this);
        back.setOnClickListener(this);
        restart.setOnClickListener(this);
        
        BeginButtonLrc beginButtonLrc=new BeginButtonLrc();
        bt_showlrc.setOnClickListener(beginButtonLrc);
    }
    //歌词
    class BeginButtonLrc implements OnClickListener{

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //创建一个Intent对象,用于同时Service开始播放MP3
            //读取LRC文件
            prepareLrc(Environment.getExternalStorageDirectory().toString()+"/"+lrcName);
            //启动Service
            //将begin的值置为当前毫秒数
            begin = System.currentTimeMillis();
        
            //执行updateTimeCallback
            handlerLrc.postDelayed(updateTimeCallback, 1);
            isPause = false;            
        }
        
    }

    private void initView2() {
        //tv_name = (TextView) findViewById(R.id.song_name);
        //tv_person=(TextView) findViewById(R.id.tv_person);
        tv_all=(TextView) findViewById(R.id.tv_all);
        tv_zou=(TextView) findViewById(R.id.tv_zou);
        sb = (SeekBar) findViewById(R.id.sb);
        // 水平滚动view
        hsv = (HorizontalScrollView) findViewById(R.id.hsv);
        ll1 = (LinearLayout) findViewById(R.id.ll1);
        ll3 = (LinearLayout) findViewById(R.id.ll3);
        // 获取屏幕分辨率
        DisplayMetrics outMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        // 拿到屏幕宽度和高度
        width = outMetrics.widthPixels;
        heigth = outMetrics.heightPixels;
        // 设置屏幕宽
        ll1.setMinimumWidth(width);
        ll3.setMinimumWidth(width);
        // 注册touch事件
        // 注册touch事件
        hsv.setOnTouchListener(this);
        sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                if (fromUser) {
                    myService.player.seekTo(progress);
                }
            }
        });
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            double x = (Double) msg.obj;
            // 滑动到某个位置
            hsv.smoothScrollTo((int) x, 0);
        };
    };

    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        int action = event.getAction();
        switch (action) {
        // 监听手松开的事件
        case MotionEvent.ACTION_UP:
            // do something
            // 获取水平滑动控件左边滑出去的距离
            int left = hsv.getScrollX();
            Message msg = handler.obtainMessage();
            if (left < 0.5 * width) {
                // 回到第一个页面,第一页的位置是0.0
                msg.obj = 0.0;
            } else if (left >= 0.5 * width && left < 1.5 * width) {
                // 回到第二页,第二页的位置是0.8倍屏幕宽度
                msg.obj = 1.0 * width;
            }
            // 发送消息
            msg.sendToTarget();
            break;

        default:
            break;
        }
        return false;
    }

    private class Myasyn extends AsyncQueryHandler {

        public Myasyn(ContentResolver cr) {
            super(cr);
            // TODO Auto-generated constructor stub
        }

        @Override
        protected Handler createHandler(Looper looper) {
            // TODO Auto-generated method stub
            return super.createHandler(looper);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            // TODO Auto-generated method stub
            super.onQueryComplete(token, cookie, cursor);
            // change adapter
            if (adapter != null) {
                adapter.changeCursor(cursor);
            }
        }
    }

}

 

 

posted @ 2014-08-07 13:25  hefen84  阅读(235)  评论(0)    收藏  举报