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进行界面交互

public class MusicService extends Service{private List<File> musicList;private MediaPlayer player;private int curPage;public static final String MFILTER = "broadcast.intent.action.text";public static final String NAME = "name";public static final String TOTALTIME = "totaltime";public static final String CURTIME = "curtime";@Overridepublic IBinder onBind(Intent intent) {//1// TODO Auto-generated method stubreturn new MBinder();}public class MBinder extends Binder{//2public MusicService getService(){return MusicService.this;} public MediaPlayer getPlayer(){return player;}}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();musicList = new ArrayList<File>();File rootDir = Environment.getExternalStorageDirectory();//3Log.d("rootname",rootDir.getName());Log.d("rootname",rootDir.getAbsolutePath());fillMusicList(rootDir);Log.d("musiclist",String.valueOf(musicList.size()));player = new MediaPlayer();if (musicList.size() != 0) {startPlay();}player.setOnCompletionListener(new OnCompletionListener() {@Overridepublic void onCompletion(MediaPlayer mp) {// TODO Auto-generated method stubplayer.reset();curPage = curPage==musicList.size()-1? (curPage+1)%musicList.size() : curPage+1; startPlay();}});}/*迭代获取 音乐 文件*/private void fillMusicList(File dir){File[] sourceFiles = dir.listFiles();Log.d("长度",String.valueOf(sourceFiles.length));for(File file : sourceFiles){if (file.isDirectory()) {Log.d("文件夹名称",String.valueOf(file.getName()));//if (!file.getName().equals("lost+found")) {fillMusicList(file);//}}else {String name = file.getName();Log.d("childname",file.getName());if (name.endsWith(".mp3")||name.endsWith(".acc")) {//支持的格式musicList.add(file);}}}}private void startPlay(){mSendBroadCast(NAME,musicList.get(curPage).getName());//4try {player.setDataSource(musicList.get(curPage).getAbsolutePath());player.prepare();player.start();player.getDuration();mSendBroadCast(TOTALTIME,player.getDuration());Timer timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubmSendBroadCast(CURTIME,player.getCurrentPosition());}},0,1000);} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void playNext(){curPage = curPage==musicList.size()-1? (curPage+1)%musicList.size() : curPage+1; Log.d("curpage",String.valueOf(curPage));player.reset();startPlay();}public void playPrevious(){curPage = curPage==0? 0 : curPage-1; Log.d("curpage",String.valueOf(curPage));player.reset();startPlay();}public void parse(){player.pause();}public void restart(){player.start();}private void mSendBroadCast(String key, String value){Intent intent = new Intent(MFILTER);intent.putExtra(key,value);//发送广播sendBroadcast(intent);}private void mSendBroadCast(String key, int value){Intent intent = new Intent(MFILTER);intent.putExtra(key,value);//发送广播sendBroadcast(intent);}}

接下来上activity代码:

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

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

3、通过receiver刷新页面

public class MainActivity extends Activity implements OnClickListener{SeekBar seekBar;TextView curTime,totalTime;TextView title;private ServiceConnection sc;private MusicService ms;private boolean isStop;private double totalTimeInt; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);IntentFilter filter = new IntentFilter(MusicService.MFILTER);registerReceiver(new MusicReceiver(),filter);sc = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stubms = null;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubms = ((MBinder)service).getService();//1}};Button previous = (Button) findViewById(R.id.previous);Button next = (Button) findViewById(R.id.next);Button stop = (Button) findViewById(R.id.stop);Button stopService = (Button) findViewById(R.id.stopService);seekBar = (SeekBar) findViewById(R.id.mSeekbar);curTime = (TextView) findViewById(R.id.curTime);totalTime = (TextView) findViewById(R.id.totalTime);title = (TextView) findViewById(R.id.title);previous.setOnClickListener(this);next.setOnClickListener(this);stop.setOnClickListener(this);stopService.setOnClickListener(this);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.previous:ms.playPrevious();//2break;case R.id.next:ms.playNext();break;case R.id.stop:if (isStop) { ms.restart();}else {ms.parse();}isStop = !isStop;break;case R.id.stopService:Intent intent = new Intent("com.intent.musicplayer.MusicService");unbindService(sc);stopService(intent);break;default:break;}}@Overrideprotected void onStart() {// TODO Auto-generated method stubsuper.onStart();Intent intent = new Intent("com.intent.musicplayer.MusicService");bindService(intent,sc,Context.BIND_AUTO_CREATE);//当然你可以用startService的方式启动服务,这样结束了activity以后并不会结束service}private String transferMilliToTime(int millis){DateFormat format = new SimpleDateFormat("mm:ss");String result = format.format(new Date(millis));return result;}private class MusicReceiver extends BroadcastReceiver{//[email protected] void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubif (intent.getIntExtra(MusicService.CURTIME,0)!=0) {double curTimeInt = intent.getIntExtra(MusicService.CURTIME,0);curTime.setText(transferMilliToTime((int)curTimeInt));double result = curTimeInt/totalTimeInt*100;seekBar.setProgress((int) Math.floor(result));}else if(intent.getIntExtra(MusicService.TOTALTIME,0)!=0) {totalTimeInt = intent.getIntExtra(MusicService.TOTALTIME,0);totalTime.setText(transferMilliToTime((int)(totalTimeInt)));}else if (!TextUtils.isEmpty(intent.getStringExtra(MusicService.NAME))) {title.setText(intent.getStringExtra(MusicService.NAME));}}}}

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

<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:orientation="vertical"tools:context="${relativePackage}.${activityClass}" ><TextView android:id="@+id/title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:textSize="25sp"android:textColor="#444444"/><SeekBar android:id="@+id/mSeekbar"android:layout_gravity="center_horizontal"android:layout_width="400dp"android:layout_height="wrap_content"android:max="100"/><RelativeLayout android:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/curTime"android:layout_height="wrap_content"android:layout_width="wrap_content"android:layout_alignParentLeft="true"/><TextViewandroid:id="@+id/totalTime"android:layout_height="wrap_content"android:layout_width="wrap_content"android:layout_alignParentRight="true"/></RelativeLayout><RelativeLayout android:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:id="@+id/previous"android:layout_height="wrap_content"android:layout_width="wrap_content"android:text="上一曲"android:layout_alignParentLeft="true"/><Button android:id="@+id/stop"android:layout_height="wrap_content"android:layout_width="wrap_content"android:text="停止音乐"android:layout_toRightOf="@id/previous"/><Buttonandroid:id="@+id/next"android:layout_height="wrap_content"android:layout_width="wrap_content"android:text="下一曲"android:layout_alignParentRight="true"/> <Button android:id="@+id/stopService"android:layout_height="wrap_content"android:layout_width="wrap_content"android:text="停止音乐服务"android:layout_toLeftOf="@id/next"/></RelativeLayout></LinearLayout>

分享给朋友:
您可能感兴趣的文章:
随机阅读: