- 初始化UI
- 初始化播放列表
- 开始/暂停
- 上一曲/下一曲
- SeekBar
- 1、MediaPlayer播放控制Seekbar
- 2、SeekBar拖拽控制MediaPlayer
- 思考:如何实现SeekBar拖拽更新Plaeyr进度?
- 提示;1、OnSeekBarChangeListener
- 2、给播放器设置当前进度:player.seekTo(progress)
MainActivity
public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private static SeekBar seekBar;
private static TextView curTimeTextView;
private static TextView maxTimeTextView;
private static SimpleDateFormat format;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initReceiver();
initPath();
}
// 初始化视图
private void initView() {
seekBar = (SeekBar) findViewById(R.id.seek_bar);
seekBar.setOnSeekBarChangeListener(this);
curTimeTextView = (TextView) findViewById(R.id.cur_time_tv);
maxTimeTextView = (TextView) findViewById(R.id.max_time_tv);
}
// 初始化广播接收器
private void initReceiver() {
format = new SimpleDateFormat("mm:ss");
ProgressReceiver receiver = new ProgressReceiver();
IntentFilter filter = new IntentFilter(PlayService.ACTION_PROGRESS);
registerReceiver(receiver, filter);
MaxReceiver maxReceiver = new MaxReceiver();
IntentFilter maxFilter = new IntentFilter(PlayService.ACTION_MAX);
registerReceiver(maxReceiver, maxFilter);
}
// 初始化播放音乐路径
private void initPath() {
// 获取音乐所在文件夹
File playPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
// 遍历音乐路径
File[] files = playPath.listFiles();
String[] paths = new String[files.length];
for (int i = 0; i < files.length; i++) {
paths[i] = files[i].getAbsolutePath();
}
// 播放路径作为参数传递给Service并做相应初始化
Intent intent = new Intent(this, PlayService.class);
intent.putExtra("paths", paths);
intent.putExtra("flag", PlayService.FLAG_LOAD_PATH);
startService(intent);
}
// 开始/暂停播放
public void play(View view) {
startServicce(PlayService.FLAG_PLAY);
}
// 上一曲
public void previous(View view) {
startServicce(PlayService.FLAG_PREVIOUS);
}
// 下一曲
public void next(View view) {
startServicce(PlayService.FLAG_NEXT);
}
// 向Service发出指令
private void startServicce(int flag) {
Intent intent = new Intent(this, PlayService.class);
intent.putExtra("flag", flag);
startService(intent);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean isFromUser) {
if (isFromUser) {// 手动拖拽更新进度
Intent intent = new Intent(this, PlayService.class);
intent.putExtra("flag", PlayService.FLAG_PROGRESS);
intent.putExtra("progress", progress);
startService(intent);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
// 接收播放进度的广播接收器
private static class ProgressReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 接收当前进度,更新SeekBar的进度
int progress = intent.getIntExtra("progress", 0);
seekBar.setProgress(progress);
String curTime = MainActivity.format.format(new Date(progress));
curTimeTextView.setText(curTime);
}
}
// 接收最大进度的广播接收器
private static class MaxReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int max = intent.getIntExtra("max", 0);
String maxTime = format.format(new Date(max));
maxTimeTextView.setText(maxTime);
seekBar.setMax(max);
}
}
}
service
public class PlayService extends Service {
// 操作标记
public static final int FLAG_LOAD_PATH = 0;// 加载播放列表
public static final int FLAG_PLAY = 1;// 开始/暂停
public static final int FLAG_PREVIOUS = 2;// 上一首
public static final int FLAG_NEXT = 3;// 下一首
public static final int FLAG_PROGRESS = 4;// 更新进度
public static final String ACTION_PROGRESS = "progress_action";// 发送当前进度的广播的动作
public static final String ACTION_MAX = "max_action";// 发送最大进度的广播的动作
// 播放列表
private String[] paths;
// 媒体播放器
private MediaPlayer player;
// 当前播放音乐的下角标
private int curIndex;
private Timer timer;
public PlayService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
// 初始化媒体播放器
player = new MediaPlayer();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
int flag = intent.getIntExtra("flag", -1);
switch (flag) {
case FLAG_LOAD_PATH:// 加载播放列表
paths = intent.getStringArrayExtra("paths");
sendMaxProgress();
break;
case FLAG_PLAY:// 播放/暂停
if (player.isPlaying()) {
// 暂停
player.pause();
} else {
// 播放
play(curIndex);
}
break;
case FLAG_PREVIOUS:// 上一曲
if (curIndex > 0) {
// 重置播放器资源
player.reset();
play(--curIndex);
}
break;
case FLAG_NEXT:// 下一首
if (curIndex < paths.length - 1) {
player.reset();
play(++curIndex);
}
break;
case FLAG_PROGRESS:// 更新播放进度
int progress = intent.getIntExtra("progress", 0);
player.seekTo(progress);
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
// 播放指定歌曲
private void play(int index) {
try {
// 设置播放文件的路径
player.setDataSource(paths[index]);
// 播放器执行准备工作,获取播放音乐信息,例如音乐长度
player.prepare();
// 通知SeekBar设置最大值
sendMaxProgress();
} catch (Exception e) {
e.printStackTrace();
}
// 播放音乐
player.start();
// 音乐播放后,控制SeekBar进度
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Log.d("1622", "timer" + Thread.currentThread().getName());
// 每隔1s发送一次广播,携带当前进度。主界面不断接收到广播,执行SeekBat更新进度的操作
Intent intent = new Intent(ACTION_PROGRESS);
intent.putExtra("progress", player.getCurrentPosition());// 获取当前播放进度
sendBroadcast(intent);
}
}, 0, 1000);
}
// 获取音乐最大进度,并使用广播通知SeekBar
private void sendMaxProgress() {
Intent intent = new Intent(ACTION_MAX);
intent.putExtra("max", player.getDuration());// 每首音乐的完整时间
sendBroadcast(intent);
}
@Override
public void onDestroy() {
if (timer != null) {
timer.cancel();
timer = null;
}
player.stop();
player.release();// 释放资源
}
}
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="org.mobiletrain.android23_startserviceplaymusicdemo.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/cur_time_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"/>
<TextView
android:id="@+id/max_time_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:layout_alignParentRight="true"/>
<SeekBar
android:id="@+id/seek_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/cur_time_tv"
android:layout_toLeftOf="@id/max_time_tv"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="上一曲"
android:onClick="previous"/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="开始/暂停"
android:onClick="play"/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="下一曲"
android:onClick="next"/>
</LinearLayout>
</LinearLayout>
清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.mobiletrain.android23_startserviceplaymusicdemo">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<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=".service.PlayService"
android:enabled="true"
android:exported="true"></service>
</application>
</manifest>
自己往手机外部存储里拖音乐