音乐播放带进度条

清单注册

<service android:name=".SeekMusicService">service>

SeekMusicService

public class SeekMusicService extends Service {

    private MediaPlayer player;
    private PlayerBroadCastReceiver receiver;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this,R.raw.wlxq);

        registerReceiver();
    }

    private void registerReceiver() {
        receiver = new PlayerBroadCastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Cans.ACTION_PLAYER);
        registerReceiver(receiver, filter);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int flag = intent.getIntExtra("flag", 0);
        switch (flag) {
            case 1:
                playMusic();
                break;
            case 2:
                stopMusic();
                break;

            default:
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    // 停止播放音乐
    private void stopMusic() {
        if (player != null && player.isPlaying()) {
            player.stop();
            player.release();
            player = null;
        }
    }

    // 播放音乐
    private void playMusic() {
        if (player == null) {
            player = MediaPlayer.create(this, R.raw.wlxq);
        }

        if (player != null && !player.isPlaying()) {
            player.start();
            // 开始线程时刻获取播放进度
            new ProgressThread().start();

        }

    }

    class ProgressThread extends Thread {
        @Override
        public void run() {
            super.run();
            if (player != null) {
                Intent intent = new Intent();
                intent.setAction(Cans.ACTION_PLAY_SEEK);
                // 获取播放的总长度

                try {

                    int maxLength = player.getDuration();
                    while (player != null && player.isPlaying()) {

                        // 拿到获取的长度与当前播放的进度发送一个广播更新进度条
                        int currentPosition = player.getCurrentPosition();
                        intent.putExtra(Cans.FLAG_MAX, maxLength);
                        intent.putExtra(Cans.FLAG_CURRENTPOSITION, currentPosition);

                        sendBroadcast(intent);

                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    }

    class PlayerBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            int progress = intent.getIntExtra(Cans.FLAG_CURRENTPOSITION, 0);
            try {

                if (player != null) {
                    // 调节到一个播放进度
                    player.seekTo(progress);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        stopMusic();
        unregisterReceiver(receiver);
    }

}

mainActivity

public class MainActivity extends AppCompatActivity {

    private TextView time_tv;
    private SeekBar seekBar;
    private Intent intent;
    private SeekBroadCastReceiver seekReceiver;
    private Intent seekIntent;
    private SimpleDraweeView mMytp;
    /**
     * 开始播放
     */
    private Button mStartBt;
    /**
     * 停止播放
     */
    private Button mEndBt;
    private SeekBar mSeekBar;
    /**
     * 00:00/00:00
     */
    private TextView mTimeTv;
    private ObjectAnimator animator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        Uri uri = Uri.parse("" + R.drawable.a);
        mMytp.setImageURI("https://ps.ssl.qhimg.com/t01d7de9ec9fd9ce918.png");
        intent = new Intent(this, SeekMusicService.class);
        seekIntent = new Intent();
        registerReceiver();
        setListener();
        animator= ObjectAnimator.ofFloat(mMytp, "rotation", 0f, 360.0f);
        animator.setDuration(2000);
        animator.setInterpolator(new LinearInterpolator());//不停顿
        animator.setRepeatCount(-1);//设置动画重复次数
        animator.setRepeatMode(ValueAnimator.RESTART);//动画重复模式
    }

    // 设置seekBar监听
    private void setListener() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止拖拽的时候
                // 获取当前seekBar 的进度
                int progress = seekBar.getProgress();
                seekIntent.setAction(Cans.ACTION_PLAYER);
                seekIntent.putExtra(Cans.FLAG_CURRENTPOSITION, progress);
                sendBroadcast(seekIntent);

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 开始拖拽的时候
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 拖拽过程中
            }
        });
    }

    // 注册接收广播
    private void registerReceiver() {
        seekReceiver = new SeekBroadCastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Cans.ACTION_PLAY_SEEK);
        registerReceiver(seekReceiver, filter);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start_bt:
                intent.putExtra("flag", 1);
                animator.start();
                break;
            case R.id.end_bt:
                intent.putExtra("flag", 2);
                animator.pause();
                break;

            default:
                break;
        }
        startService(intent);
    }

    private void initView() {
        mMytp = (SimpleDraweeView) findViewById(R.id.mytp);
        time_tv = (Button) findViewById(R.id.start_bt);
        mEndBt = (Button) findViewById(R.id.end_bt);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        time_tv = (TextView) findViewById(R.id.time_tv);
    }

    // 接收从服务端发送过来的 进度
    class SeekBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            int max = intent.getIntExtra(Cans.FLAG_MAX, 0);
            int currentPosition = intent.getIntExtra(Cans.FLAG_CURRENTPOSITION, 0);

            // 设置seekBar的最大值
            seekBar.setMax(max);
            // 设置seekBar的当前位置
            seekBar.setProgress(currentPosition);

            // 计算最大值的时间
            int maxMinute = max / 1000 / 60;
            int maxSecond = max / 1000 % 60;

            // 计算当前播放的时间
            int currentMinute = currentPosition / 1000 / 60;
            int currentSecond = currentPosition / 1000 % 60;

            StringBuffer buffer = new StringBuffer();

            buffer.append(currentMinute / 10).append(currentMinute % 10).append(":").append(currentSecond / 10)
                    .append(currentSecond % 10).append("/").append(maxMinute / 10).append(maxMinute % 10).append(":")
                    .append(maxSecond / 10).append(maxSecond % 10);
            // 更新时间显示
            time_tv.setText(buffer.toString());

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(seekReceiver);
    }
}
布局

xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="7">

        <com.facebook.drawee.view.SimpleDraweeView
            android:id="@+id/mytp"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_centerInParent="true"
            fresco:roundAsCircle="true" />
    RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">


            <Button
                android:id="@+id/start_bt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:onClick="onClick"
                android:text="开始播放"
                tools:ignore="OnClick" />

            <Button
                android:id="@+id/end_bt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/start_bt"
                android:layout_centerHorizontal="true"
                android:onClick="onClick"
                android:text="停止播放"
                tools:ignore="OnClick" />

            <SeekBar
                android:id="@+id/seekBar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/start_bt" />

            <TextView
                android:id="@+id/time_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/seekBar"
                android:text="00:00/00:00" />
        RelativeLayout>
    LinearLayout>
LinearLayout>

你可能感兴趣的:(音乐播放带进度条)