2024年3月28日发(作者:)
音乐播放之进度条
[前提]
* android 自身也提供了该接口 似乎是:MediaController 但看过截图 发现极丑 所以今天就自己写了一
个 现于诸位分享分享
[要求]
1. 进度条控件打算使用系统提供的SeekBar
2. SeekBar 要支持拖拉功能 即:定点播放
3. SeekBar 要反映播放位置 即:播放到哪 SeekBar 就在哪
[原理]
1. 音乐定点播放:(int msecond) //单位:毫秒
2. 音乐文件播放时间:ation()
3. SeekBar 获取位置:gress()
4. SeekBar 最大值: ()
[代码 步骤]
1. 定义界面:
Java代码
1. 1 * Button : 播放控制 如:暂停 继续
2. 1 * TextView : 显示播放百分比
3. 1 * SeekBar : 进度条
4. 1 * RadioGroup : 显示所有sdcard 音乐文件
Java代码
1.
2. roid">/apk/res/android" 3. android:orientation="vertical" 4. android:layout_width="fill_parent" 5. android:layout_height="fill_parent" 6. > 7. roid">/apk/res/android" 8. android:orientation="horizontal" 9. android:layout_width="fill_parent" 10. android:layout_height="wrap_content" 11. > 12. 28. 29. android:id="@+id/seekb" 30. android:max="100" 31. android:layout_width="fill_parent" 32. android:layout_height="wrap_content" 33. /> 34.
2. View 初始化
Java代码
1. public void initialize(){
2.
3. sBar = (SeekBar)findViewById();
4. rGroup = (RadioGroup)findViewById();
5. cmdButton = (Button)findViewById();
6.
7. mPlayer = new MediaPlayer();
8. }
3. 拖动SeekBar 且播放指定位置的音乐
Java代码
1. eekBarChangeListener(new OnSeekBarChangeListener(){
2.
3. @Override
4. public void onProgressChanged(SeekBar seekBar, int progress,
5. boolean fromUser) {
6. // TODO Auto-generated method stub
7.
8. }
9.
10. @Override
11. public void onStartTrackingTouch(SeekBar seekBar) {
12. // TODO Auto-generated method stub
13. }
14.
15. @Override
16. public void onStopTrackingTouch(SeekBar seekBar) {
17. // TODO Auto-generated method stub
18. int dest = gress();
19.
20. int mMax = ation();
21. int sMax = ();
22.
23. (mMax*dest/sMax);
24.
25. }
26.
27. });
4. 刷新播放位置 且使其实时变化
//因为MediaPlayer没有播放进度的回调函数 所以只能:开辟一个Thread 定时通知其刷新
Java代码
1. public void startProgressUpdate(){
2. //开辟Thread 用于定期刷新SeekBar
3. DelayThread dThread = new DelayThread(100);
4. ();
5. }
而该Thread 具体实现为:
Java代码
1. private Handler mHandle = new Handler(){
2. @Override
3. public void handleMessage(Message msg){
4. int position = rentPosition();
5.
6. int mMax = ation();
7. int sMax = ();
8.
9. gress(position*sMax/mMax);
10. }
11. };
12.
13. public class DelayThread extends Thread {
14. int milliseconds;
15.
16. public DelayThread(int i){
17. milliseconds = i;
18. }
19. public void run() {
20. while(true){
21. try {
22. sleep(milliseconds);
23. } catch (InterruptedException e) {
24. // TODO Auto-generated catch block
25. tackTrace();
26. }
27.
28. ptyMessage(0);
29. }
30. }
31. }
5. emulator 运行截图:


发布评论