音乐播放器中综合了以下内容:
SeekBar、ListView、广播接收者(以代码的形式注册Receiver)、系统服务、MediaPlayer
实现的功能:
1.暂停/播放、下一首/上一首,点击某一首时播放
2.支持拖动进度条快进
3.列表排序
4.来电话时,停止播放,挂断后继续播放
5.可在后台播放
效果图:
界面:
main.xml:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/name"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <SeekBar
- android:id="@+id/seekBar"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginBottom="5dp"
- />
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginBottom="20dp"
- >
- <Button
- android:layout_width="40dp"
- android:layout_height="40dp"
- android:text="|◀"
- android:onClick="previous"
- />
- <Button
- android:id="@+id/pp"
- android:layout_width="40dp"
- android:layout_height="40dp"
- android:text="▶"
- android:onClick="pp"
- />
- <Button
- android:layout_width="40dp"
- android:layout_height="40dp"
- android:text="▶|"
- android:onClick="next"
- />
- </LinearLayout>
- <ListView
- android:id="@+id/list"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- />
- </LinearLayout>
item.xml:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:padding="10dp"
- >
- <TextView
- android:id="@+id/mName"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:textSize="15sp"
- />
- </LinearLayout>
MainActivity:
- packagecn.test.audio;
- importjava.io.File;
- importjava.util.ArrayList;
- importjava.util.Collections;
- importjava.util.HashMap;
- importjava.util.List;
- importjava.util.Map;
- importandroid.app.Activity;
- importandroid.content.BroadcastReceiver;
- importandroid.content.Context;
- importandroid.content.Intent;
- importandroid.content.IntentFilter;
- importandroid.media.MediaPlayer;
- importandroid.media.MediaPlayer.OnCompletionListener;
- importandroid.os.Bundle;
- importandroid.os.Environment;
- importandroid.os.Handler;
- importandroid.telephony.PhoneStateListener;
- importandroid.telephony.TelephonyManager;
- importandroid.view.View;
- importandroid.widget.AdapterView;
- importandroid.widget.Button;
- importandroid.widget.ListView;
- importandroid.widget.SeekBar;
- importandroid.widget.SimpleAdapter;
- importandroid.widget.TextView;
- importandroid.widget.AdapterView.OnItemClickListener;
- importandroid.widget.SeekBar.OnSeekBarChangeListener;
- publicclassMainActivityextendsActivity{
- privateTextViewnameTextView;
- privateSeekBarseekBar;
- privateListViewlistView;
- privateList<Map<String,String>>data;
- privateintcurrent;
- privateMediaPlayerplayer;
- privateHandlerhandler=newHandler();
- privateButtonppButton;
- privatebooleanisPause;
- privatebooleanisStartTrackingTouch;
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- nameTextView=(TextView)findViewById(R.id.name);
- seekBar=(SeekBar)findViewById(R.id.seekBar);
- listView=(ListView)findViewById(R.id.list);
- ppButton=(Button)findViewById(R.id.pp);
- //创建一个音乐播放器
- player=newMediaPlayer();
- //显示音乐播放列表
- generateListView();
- //进度条监听器
- seekBar.setOnSeekBarChangeListener(newMySeekBarListener());
- //播放器监听器
- player.setOnCompletionListener(newMyPlayerListener());
- //意图过滤器
- IntentFilterfilter=newIntentFilter();
- //播出电话暂停音乐播放
- filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
- registerReceiver(newPhoneListener(),filter);
- //创建一个电话服务
- TelephonyManagermanager=(TelephonyManager)getSystemService(TELEPHONY_SERVICE);
- //监听电话状态,接电话时停止播放
- manager.listen(newMyPhoneStateListener(),PhoneStateListener.LISTEN_CALL_STATE);
- }
- /*
- *监听电话状态
- */
- privatefinalclassMyPhoneStateListenerextendsPhoneStateListener{
- publicvoidonCallStateChanged(intstate,StringincomingNumber){
- pause();
- }
- }
- /*
- *播放器监听器
- */
- privatefinalclassMyPlayerListenerimplementsOnCompletionListener{
- //歌曲播放完后自动播放下一首歌曲
- publicvoidonCompletion(MediaPlayermp){
- next();
- }
- }
- /*
- *下一首按钮
- */
- publicvoidnext(Viewview){
- next();
- }
- /*
- *前一首按钮
- */
- publicvoidprevious(Viewview){
- previous();
- }
- /*
- *播放前一首歌
- */
- privatevoidprevious(){
- current=current-1<0?data.size()-1:current-1;
- play();
- }
- /*
- *播放下一首歌
- */
- privatevoidnext(){
- current=(current+1)%data.size();
- play();
- }
- /*
- *进度条监听器
- */
- privatefinalclassMySeekBarListenerimplementsOnSeekBarChangeListener{
- //移动触发
- publicvoidonProgressChanged(SeekBarseekBar,intprogress,booleanfromUser){
- }
- //起始触发
- publicvoidonStartTrackingTouch(SeekBarseekBar){
- isStartTrackingTouch=true;
- }
- //结束触发
- publicvoidonStopTrackingTouch(SeekBarseekBar){
- player.seekTo(seekBar.getProgress());
- isStartTrackingTouch=false;
- }
- }
- /*
- *显示音乐播放列表
- */
- privatevoidgenerateListView(){
- List<File>list=newArrayList<File>();
- //获取sdcard中的所有歌曲
- findAll(Environment.getExternalStorageDirectory(),list);
- //播放列表进行排序,字符顺序
- Collections.sort(list);
- data=newArrayList<Map<String,String>>();
- for(Filefile:list){
- Map<String,String>map=newHashMap<String,String>();
- map.put("name",file.getName());
- map.put("path",file.getAbsolutePath());
- data.add(map);
- }
- SimpleAdapteradapter=newSimpleAdapter(this,data,R.layout.item,newString[]{"name"},newint[]{R.id.mName});
- listView.setAdapter(adapter);
- listView.setOnItemClickListener(newMyItemListener());
- }
- privatefinalclassMyItemListenerimplementsOnItemClickListener{
- publicvoidonItemClick(AdapterView<?>parent,Viewview,intposition,longid){
- current=position;
- play();
- }
- }
- privatevoidplay(){
- try{
- //重播
- player.reset();
- //获取歌曲路径
- player.setDataSource(data.get(current).get("path"));
- //缓冲
- player.prepare();
- //开始播放
- player.start();
- //显示歌名
- nameTextView.setText(data.get(current).get("name"));
- //设置进度条长度
- seekBar.setMax(player.getDuration());
- //播放按钮样式
- ppButton.setText("||");
- //发送一个Runnable,handler收到之后就会执行run()方法
- handler.post(newRunnable(){
- publicvoidrun(){
- //更新进度条状态
- if(!isStartTrackingTouch)
- seekBar.setProgress(player.getCurrentPosition());
- //1秒之后再次发送
- handler.postDelayed(this,1000);
- }
- });
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- /**
- *查找文件路径中所有mp3文件
- *@paramfile要找的目录
- *@paramlist用来装文件的List
- */
- privatevoidfindAll(Filefile,List<File>list){
- File[]subFiles=file.listFiles();
- if(subFiles!=null)
- for(FilesubFile:subFiles){
- if(subFile.isFile()&&subFile.getName().endsWith(".mp3"))
- list.add(subFile);
- elseif(subFile.isDirectory())//如果是目录
- findAll(subFile,list);//递归
- }
- }
- /*
- *暂停/播放按钮
- */
- publicvoidpp(Viewview){
- //默认从第一首歌曲开始播放
- if(!player.isPlaying()&&!isPause){
- play();
- return;
- }
- Buttonbutton=(Button)view;
- //暂停/播放按钮
- if("||".equals(button.getText())){
- pause();
- button.setText("▶");
- }else{
- resume();
- button.setText("||");
- }
- }
- /*
- *开始操作
- */
- privatevoidresume(){
- if(isPause){
- player.start();
- isPause=false;
- }
- }
- /*
- *暂停操作
- */
- privatevoidpause(){
- if(player!=null&&player.isPlaying()){
- player.pause();
- isPause=true;
- }
- }
- /*
- *收到广播时暂停
- */
- privatefinalclassPhoneListenerextendsBroadcastReceiver{
- publicvoidonReceive(Contextcontext,Intentintent){
- pause();
- }
- }
- /*
- *恢复播放
- *@seeandroid.app.Activity#onResume()
- */
- protectedvoidonResume(){
- super.onResume();
- resume();
- }
- }
注册权限:
- <?xmlversion="1.0"encoding="utf-8"?>
- <manifestxmlns:android="http://schemas.android.com/apk/res/android"
- package="cn.itcast.audio"
- android:versionCode="1"
- android:versionName="1.0">
- <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
- <activityandroid:name=".MainActivity"
- android:label="@string/app_name">
- <intent-filter>
- <actionandroid:name="android.intent.action.MAIN"/>
- <categoryandroid:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
- </application>
- <uses-sdkandroid:minSdkVersion="8"/>
- <!--监听电话呼出-->
- <uses-permissionandroid:name="android.permission.PROCESS_OUTGOING_CALLS"/>
- <!--监听电话状态改变-->
- <uses-permissionandroid:name="android.permission.READ_PHONE_STATE"/>
- </manifest>
非常反感源码 但是还是共享一下 帮助大家共同学习。。。。。