带进度条的播放音乐

MainActivity内容

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView time_tv;
    private SeekBar seekBar;
    private Intent intent;
    private SeekBroadCastReceiver seekReceiver;
    private Intent seekIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        time_tv = (TextView) findViewById(R.id.time_tv);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        intent = new Intent(this, SeekMusicService.class);
        seekIntent = new Intent();
        registerReceiver();
        setListener();
    }

    // 设置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);
                break;
            case R.id.end_bt:
                intent.putExtra("flag", 2);
                break;

            default:
                break;
        }
        startService(intent);
    }

    // 接收从服务端发送过来的 进度
    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);
    }
}

SeekMusicService内容**

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;

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);
    }

}

Cans类

public class Cans {
    // 服务 播放 通知 seekBar 修改进度
    public static final String ACTION_PLAY_SEEK = "com..bw.alice.servicestartseekbar.seek";
    // seekBar 通知 服务修改player的进度
    public static final String ACTION_PLAYER = "com..bw.alice.servicestartseekbar.play";
    // 当前时长的标记
    public static final String FLAG_MAX = "flag_max";
    // 当前 播放的 位置的标记
    public static final String FLAG_CURRENTPOSITION = "flag_currentposition";
    public static final String FLAG_SEEKPOSITION = "flag_seek_currentposition";

}

activity_main布局

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bw.alice.servicestartseekbar.MainActivity">


    <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="开始播放" />

    <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="停止播放" />

    <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>

清单文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.bw.alice.servicestartseekbar">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <service android:name=".SeekMusicService"/>
    </application>

</manifest>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值