读取SD卡文件夹下的MP3文件和播放MP3文件

时间:2021-06-01 15:16:38

  首先获取SD卡path路径下的所有的MP3文件,并将文件名和文件大小存入List数组(此代码定义在FileUtils类中):

    /**
    * 读取目录中的Mp3文件的名字和大小
    */
    public List<Mp3Info> getMp3Files(String path) {
      SDCardRoot = Environment.getExternalStorageDirectory()
        .getAbsolutePath(); //获取SD卡的路径名
      List<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();
      File file = new File(SDCardRoot + File.separator + path);
      File[] files = file.listFiles();
      for (int i = 0; i < files.length; i++) {
        if (files[i].getName().endsWith(".mp3")) {
          Mp3Info mp3Info = new Mp3Info();
          mp3Info.setMp3Name(files[i].getName());
          mp3Info.setMp3Size(files[i].length() + "");
          mp3Infos.add(mp3Info);  //此mp3Info对象中包含mp3文件名和文件大小
        }
      }
      return mp3Infos;
    }

  当前Activity继承自ListActivity,在此Activity的onResume方法中调用getMp3Files()方法,获取路径下的Mp3文件

    @Override
    protected void onResume() {
      FileUtils fileUtils = new FileUtils();
      mp3Infos = fileUtils.getMp3Files("mp3/");
      List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
      for(Iterator iterator = mp3Infos.iterator();iterator.hasNext();){
        Mp3Info mp3Info = (Mp3Info) iterator.next();
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("mp3_name", mp3Info.getMp3Name());
        map.put("size_id", mp3Info.getMp3Size());
        list.add(map);
      }
      SimpleAdapter simpleAdapter = new SimpleAdapter(this,list,R.layout.mp3info_item,new String[]{"mp3_name","size_id"},new int[]                {R.id.mp3_name,R.id.size_id});    //mp3info_item.xml文件中仅有两个TextView,id为mp3_name和size_id
      setListAdapter(simpleAdapter);
      super.onResume();
    }

  当点击当前Activity中的某一行时,播放当前行的Mp3文件:

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
      if(mp3Infos != null){
        Mp3Info mp3Info = mp3Infos.get(position);
        Intent intent = new Intent();
        intent.putExtra("mp3Info", mp3Info);
        intent.setClass(this,PlayerActivity.class);
        startActivity(intent);
      }
      super.onListItemClick(l, v, position, id);
    }

    PlayerActivity.class类中通过Service来播放选中的Mp3文件,定义如下:

      public class PlayerActivity extends Activity {

        private ImageButton beginButton = null;
        private ImageButton pauseButton = null;
        private ImageButton stopButton = null;
        private Mp3Info mp3Info = null;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
          setContentView(R.layout.player);
          super.onCreate(savedInstanceState);
          Intent intent = getIntent();
          mp3Info = (Mp3Info) intent.getSerializableExtra("mp3Info");
          beginButton = (ImageButton) findViewById(R.id.begin);
          pauseButton = (ImageButton) findViewById(R.id.pause);
          stopButton = (ImageButton) findViewById(R.id.stop);
          ButtonClickListener listener = new ButtonClickListener();
          beginButton.setOnClickListener(listener);
          pauseButton.setOnClickListener(listener);
          stopButton.setOnClickListener(listener);
        }

      class ButtonClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
          if (v.getId() == R.id.begin) { // 播放按键
            //创建一个intent对象,通知Service开始播放MP3
            Intent intent = new Intent();
            intent.setClass(PlayerActivity.this, PlayerService.class);
            intent.putExtra("mp3Info", mp3Info);
            intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG);
            //启动Service
            startService(intent);
          } else if (v.getId() == R.id.pause) {
            //通知Service暂停播放MP3
            Intent intent = new Intent();
            intent.setClass(PlayerActivity.this, PlayerService.class);
            intent.putExtra("MSG", AppConstant.PlayerMsg.PAUSE_MSG);
            startService(intent);
          } else if (v.getId() == R.id.stop) {
            //通知Service停止MP3文件
            Intent intent = new Intent();
            intent.setClass(PlayerActivity.this, PlayerService.class);
            intent.putExtra("MSG", AppConstant.PlayerMsg.STOP_MSG);
            startService(intent);
          }
        }

      }
    }

  PlayerService定义如下:

    public class PlayerService extends Service {

      private boolean isPlaying = false;
      private boolean isPause = false;
      private boolean isReleased = false;
      private MediaPlayer mediaPlayer = null;
      private Mp3Info mp3Info = null;
      private ArrayList<Queue> queues = null;

      @Override
      public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
      }

      // 每次从Activity向Service发送intent对象时,触发该事件
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
        mp3Info = (Mp3Info) intent.getSerializableExtra("mp3Info");
        int MSG = intent.getIntExtra("MSG", 0);
        if (mp3Info != null) {
          if (MSG == AppConstant.PlayerMsg.PLAY_MSG) {
            play(mp3Info);
          }
        }
        else{
          if(MSG == AppConstant.PlayerMsg.PAUSE_MSG){
            pause();
          }
          else if(MSG == AppConstant.PlayerMsg.STOP_MSG){
            stop();
          }
        }
        return super.onStartCommand(intent, flags, startId);
      }
      private void play(Mp3Info mp3Info){
        if(!isPlaying){
          String path = getMp3Path(mp3Info);
          mediaPlayer = MediaPlayer.create(this, Uri.parse("file://" + path));
          mediaPlayer.setLooping(true);   //设置歌曲循环播放
          mediaPlayer.start();
          isPlaying = true;
          isReleased = false;
        }
      }

      private void pause(){
        if(mediaPlayer != null){
          if(isPlaying){
            mediaPlayer.pause();
          } else{
            mediaPlayer.start();
          }
          isPlaying = isPlaying ? false : true;
        }
      }
      private void stop(){
        if(mediaPlayer!=null){
          if(isPlaying){
            if(!isReleased){
              mediaPlayer.stop();
              mediaPlayer.release();
              isReleased = true;
              isPlaying = false;
            }
          }
        }
      }
      private String getMp3Path(Mp3Info mp3Info){
        String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
        String path = SDCardRoot + File.separator + "mp3" + File.separator + mp3Info.getMp3Name();
        return path;
      }