首页 > 系统 > Android > 正文

教你轻松制作Android音乐播放器

2019-10-24 20:34:44
字体:
来源:转载
供稿:网友

这篇文章主要教大家轻松制作Android音乐播放器,制作一款属于自己的Android音乐播放器,希望大家喜欢。

欣赏一下我们清爽的界面吧~

教你轻松制作Android音乐播放器

如果是只用activity来制作这样的东西简直是太小儿科了,此处我们当然用的是service

首先我们先上service的代码:

1、如果我们要访问service的属性和方法,那么在activity肯定是以bindservice的方法实现的,而在service中的onbind方法也是必须要实现的,onbind返回的Ibinder对象在activity的serviceconnection中得到使用。

2、activity获取到Ibinder对象,可以进一步获取服务对象和player对象,来进行访问。

3、Environment.getExternalStorageDirectory()是获取sd中的内容的,不管是手机出场就已经内置的sd卡,还是用户后来自己添加的sd卡;而getExternalFilesDir()获取的真正是手机内部的存储空间,,/data/data/your_package/,随着应用的卸载存储的文件会被删除。

4、service通过发送广播与activity进行界面交互

 

 
  1. public class MusicService extends Service{ 
  2.  
  3. private List<File> musicList; 
  4. private MediaPlayer player; 
  5. private int curPage; 
  6. public static final String MFILTER = "broadcast.intent.action.text"
  7. public static final String NAME = "name"
  8. public static final String TOTALTIME = "totaltime"
  9. public static final String CURTIME = "curtime"
  10.  
  11. @Override 
  12. public IBinder onBind(Intent intent) {//1 
  13. // TODO Auto-generated method stub 
  14. return new MBinder(); 
  15. public class MBinder extends Binder{//2 
  16. public MusicService getService(){ 
  17. return MusicService.this
  18. }  
  19. public MediaPlayer getPlayer(){ 
  20. return player; 
  21. @Override 
  22. public void onCreate() { 
  23. // TODO Auto-generated method stub 
  24. super.onCreate(); 
  25. musicList = new ArrayList<File>(); 
  26. File rootDir = Environment.getExternalStorageDirectory();//3 
  27. Log.d("rootname",rootDir.getName()); 
  28. Log.d("rootname",rootDir.getAbsolutePath()); 
  29. fillMusicList(rootDir); 
  30. Log.d("musiclist",String.valueOf(musicList.size())); 
  31. player = new MediaPlayer(); 
  32. if (musicList.size() != 0) { 
  33. startPlay(); 
  34.  
  35. player.setOnCompletionListener(new OnCompletionListener() { 
  36.  
  37. @Override 
  38. public void onCompletion(MediaPlayer mp) { 
  39. // TODO Auto-generated method stub 
  40. player.reset(); 
  41. curPage = curPage==musicList.size()-1? (curPage+1)%musicList.size() : curPage+1;  
  42. startPlay(); 
  43. }); 
  44. /*迭代获取 音乐 文件*/ 
  45. private void fillMusicList(File dir){ 
  46. File[] sourceFiles = dir.listFiles(); 
  47. Log.d("长度",String.valueOf(sourceFiles.length)); 
  48. for(File file : sourceFiles){ 
  49. if (file.isDirectory()) { 
  50. Log.d("文件夹名称",String.valueOf(file.getName())); 
  51. // if (!file.getName().equals("lost+found")) { 
  52. fillMusicList(file); 
  53. // } 
  54.  
  55. else { 
  56. String name = file.getName(); 
  57. Log.d("childname",file.getName()); 
  58. if (name.endsWith(".mp3")||name.endsWith(".acc")) {//支持的格式 
  59. musicList.add(file); 
  60. private void startPlay(){ 
  61. mSendBroadCast(NAME,musicList.get(curPage).getName());//4 
  62. try { 
  63. player.setDataSource(musicList.get(curPage).getAbsolutePath()); 
  64. player.prepare(); 
  65. player.start(); 
  66. player.getDuration(); 
  67. mSendBroadCast(TOTALTIME,player.getDuration()); 
  68. Timer timer = new Timer(); 
  69. timer.schedule(new TimerTask() { 
  70.  
  71. @Override 
  72. public void run() { 
  73. // TODO Auto-generated method stub 
  74. mSendBroadCast(CURTIME,player.getCurrentPosition()); 
  75. },0,1000); 
  76.  
  77. catch (IllegalArgumentException e) { 
  78. // TODO Auto-generated catch block 
  79. e.printStackTrace(); 
  80. catch (SecurityException e) { 
  81. // TODO Auto-generated catch block 
  82. e.printStackTrace(); 
  83. catch (IllegalStateException e) { 
  84. // TODO Auto-generated catch block 
  85. e.printStackTrace(); 
  86. catch (IOException e) { 
  87. // TODO Auto-generated catch block 
  88. e.printStackTrace(); 
  89.  
  90.  
  91. public void playNext(){ 
  92. curPage = curPage==musicList.size()-1? (curPage+1)%musicList.size() : curPage+1;  
  93. Log.d("curpage",String.valueOf(curPage)); 
  94. player.reset(); 
  95. startPlay(); 
  96. public void playPrevious(){ 
  97. curPage = curPage==0? 0 : curPage-1;  
  98. Log.d("curpage",String.valueOf(curPage)); 
  99. player.reset(); 
  100. startPlay(); 
  101. public void parse(){ 
  102. player.pause(); 
  103. public void restart(){ 
  104. player.start(); 
  105. private void mSendBroadCast(String key, String value){ 
  106. Intent intent = new Intent(MFILTER); 
  107. intent.putExtra(key,value);//发送广播 
  108. sendBroadcast(intent); 
  109.  
  110. private void mSendBroadCast(String key, int value){ 
  111. Intent intent = new Intent(MFILTER); 
  112. intent.putExtra(key,value);//发送广播 
  113. sendBroadcast(intent); 

接下来上activity代码:

1、通过Ibinder对象获取服务对象

2、获取到服务对象以后,再访问服务的方法。

3、通过receiver刷新页面

 

 
  1. public class MainActivity extends Activity implements OnClickListener{ 
  2.  
  3. SeekBar seekBar; 
  4. TextView curTime,totalTime; 
  5. TextView title; 
  6.  
  7. private ServiceConnection sc; 
  8. private MusicService ms; 
  9. private boolean isStop; 
  10. private double totalTimeInt;  
  11. @Override 
  12. protected void onCreate(Bundle savedInstanceState) { 
  13. super.onCreate(savedInstanceState); 
  14. setContentView(R.layout.activity_main); 
  15. IntentFilter filter = new IntentFilter(MusicService.MFILTER); 
  16. registerReceiver(new MusicReceiver(),filter); 
  17. sc = new ServiceConnection() { 
  18.  
  19. @Override 
  20. public void onServiceDisconnected(ComponentName name) { 
  21. // TODO Auto-generated method stub 
  22. ms = null
  23.  
  24. @Override 
  25. public void onServiceConnected(ComponentName name, IBinder service) { 
  26. // TODO Auto-generated method stub 
  27. ms = ((MBinder)service).getService();//1 
  28.  
  29. }; 
  30. Button previous = (Button) findViewById(R.id.previous); 
  31. Button next = (Button) findViewById(R.id.next); 
  32. Button stop = (Button) findViewById(R.id.stop); 
  33. Button stopService = (Button) findViewById(R.id.stopService); 
  34. seekBar = (SeekBar) findViewById(R.id.mSeekbar); 
  35. curTime = (TextView) findViewById(R.id.curTime); 
  36. totalTime = (TextView) findViewById(R.id.totalTime); 
  37. title = (TextView) findViewById(R.id.title); 
  38.  
  39. previous.setOnClickListener(this); 
  40. next.setOnClickListener(this); 
  41. stop.setOnClickListener(this); 
  42. stopService.setOnClickListener(this); 
  43.  
  44. @Override 
  45. public void onClick(View v) { 
  46. // TODO Auto-generated method stub 
  47. switch (v.getId()) { 
  48. case R.id.previous: 
  49. ms.playPrevious();//2 
  50. break
  51. case R.id.next: 
  52. ms.playNext(); 
  53. break
  54. case R.id.stop: 
  55. if (isStop) { 
  56. ms.restart(); 
  57. else { 
  58. ms.parse(); 
  59. isStop = !isStop; 
  60. break
  61. case R.id.stopService: 
  62. Intent intent = new Intent("com.intent.musicplayer.MusicService"); 
  63. unbindService(sc); 
  64. stopService(intent); 
  65.  
  66. break
  67. default
  68. break
  69.  
  70. @Override 
  71. protected void onStart() { 
  72. // TODO Auto-generated method stub 
  73. super.onStart(); 
  74. Intent intent = new Intent("com.intent.musicplayer.MusicService"); 
  75. bindService(intent,sc,Context.BIND_AUTO_CREATE);//当然你可以用startService的方式启动服务,这样结束了activity以后并不会结束service 
  76.  
  77. private String transferMilliToTime(int millis){ 
  78. DateFormat format = new SimpleDateFormat("mm:ss"); 
  79. String result = format.format(new Date(millis)); 
  80. return result; 
  81. private class MusicReceiver extends BroadcastReceiver{//3 
  82.  
  83. @Override 
  84. public void onReceive(Context context, Intent intent) { 
  85. // TODO Auto-generated method stub 
  86. if (intent.getIntExtra(MusicService.CURTIME,0)!=0) { 
  87. double curTimeInt = intent.getIntExtra(MusicService.CURTIME,0); 
  88. curTime.setText(transferMilliToTime((int)curTimeInt)); 
  89. double result = curTimeInt/totalTimeInt*100; 
  90. seekBar.setProgress((int) Math.floor(result)); 
  91.  
  92. else if(intent.getIntExtra(MusicService.TOTALTIME,0)!=0) { 
  93. totalTimeInt = intent.getIntExtra(MusicService.TOTALTIME,0); 
  94. totalTime.setText(transferMilliToTime((int)(totalTimeInt))); 
  95. else if (!TextUtils.isEmpty(intent.getStringExtra(MusicService.NAME))) { 
  96. title.setText(intent.getStringExtra(MusicService.NAME)); 
  97.  

4、最后附上xml布局文件,算是代码上传完全了:

 

 
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2. xmlns:tools="http://schemas.android.com/tools" 
  3. android:layout_width="match_parent" 
  4. android:layout_height="match_parent" 
  5. android:orientation="vertical" 
  6. tools:context="${relativePackage}.${activityClass}" > 
  7. <TextView  
  8. android:id="@+id/title" 
  9. android:layout_width="wrap_content" 
  10. android:layout_height="wrap_content" 
  11. android:layout_gravity="center_horizontal" 
  12. android:textSize="25sp" 
  13. android:textColor="#444444" 
  14. /> 
  15. <SeekBar  
  16. android:id="@+id/mSeekbar" 
  17. android:layout_gravity="center_horizontal" 
  18. android:layout_width="400dp" 
  19. android:layout_height="wrap_content" 
  20. android:max="100" 
  21. /> 
  22. <RelativeLayout  
  23. android:layout_width="match_parent" 
  24. android:layout_height="wrap_content" 
  25. <TextView 
  26. android:id="@+id/curTime" 
  27. android:layout_height="wrap_content" 
  28. android:layout_width="wrap_content" 
  29. android:layout_alignParentLeft="true" 
  30.  
  31. /> 
  32. <TextView 
  33. android:id="@+id/totalTime" 
  34. android:layout_height="wrap_content" 
  35. android:layout_width="wrap_content" 
  36. android:layout_alignParentRight="true" 
  37. /> 
  38. </RelativeLayout> 
  39. <RelativeLayout  
  40. android:layout_width="match_parent" 
  41. android:layout_height="wrap_content" 
  42. <Button 
  43. android:id="@+id/previous" 
  44. android:layout_height="wrap_content" 
  45. android:layout_width="wrap_content" 
  46. android:text="上一曲" 
  47. android:layout_alignParentLeft="true" 
  48. /> 
  49. <Button  
  50. android:id="@+id/stop" 
  51. android:layout_height="wrap_content" 
  52. android:layout_width="wrap_content" 
  53. android:text="停止音乐" 
  54. android:layout_toRightOf="@id/previous" 
  55. /> 
  56.  
  57. <Button 
  58. android:id="@+id/next" 
  59. android:layout_height="wrap_content" 
  60. android:layout_width="wrap_content" 
  61. android:text="下一曲" 
  62. android:layout_alignParentRight="true" 
  63. /> 
  64. <Button  
  65. android:id="@+id/stopService" 
  66. android:layout_height="wrap_content" 
  67. android:layout_width="wrap_content" 
  68. android:text="停止音乐服务" 
  69. android:layout_toLeftOf="@id/next" 
  70. /> 
  71. </RelativeLayout>  
  72.  
  73. </LinearLayout> 

以上就是制作Android音乐播放器的全部代码,希望对大家的学习有所帮助。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表