首先获取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;
      }

读取SD卡文件夹下的MP3文件和播放MP3文件的更多相关文章

  1. 飞鱼相册笔记(1)----外置SD卡文件夹名称不区分大小写

    飞鱼相册笔记(1)----外置SD卡文件夹名称不区分大小写 在飞鱼相册发布的第一个测试版中,很多用户表示无法查看外置SD卡中的照片.乍一听觉得加个外置SD卡的根目录,然后在扫描所有图片的时候把这个根目 ...

  2. Android得到SD卡文件夹大小以及删除文件夹操作

    float cacheSize = dirSize(new File(Environment.getExternalStorageDirectory() + AppConstants.APP_CACH ...

  3. 遍历文件夹及其子文件夹下的.pdf文件,并解压文件夹下所有的压缩包

    List<PDFPATH> pdfpath = new List<PDFPATH>(); List<string> ziplist = new List<st ...

  4. Java 遍历指定文件夹及子文件夹下的文件

    Java 遍历指定文件夹及子文件夹下的文件 /** * 遍历指定文件夹及子文件夹下的文件 * * @author testcs_dn * @date 2014年12月12日下午2:33:49 * @p ...

  5. JAVA中删除文件夹下及其子文件夹下的某类文件

    ##定时删除拜访图片 ##cron表达式 秒 分 时 天 月 ? ##每月1日整点执行 CRON1=0 0 0 1 * ? scheduled.enable1=false ##图片路径 filePat ...

  6. 通过ftp同步服务器文件:遍历文件夹所有文件(含子文件夹、进度条);简单http同步服务器文件实例

    该代码主要实现,指定ftp服务地址,遍历下载该地址下所有文件(含子文件夹下文件),并提供进度条显示:另外附带有通过http地址方式获取服务器文件的简单实例 废话不多说,直接上代码: 1.FTPHelp ...

  7. 安卓下对SD卡文件的读写

    为SD下的操作文件,封装了一些类: package ujs.javawritedata; import java.io.File; import java.io.FileInputStream; im ...

  8. asp.net(C#)读取文件夹和子文件夹下所有文件,绑定到GRIDVIEW并排序 .

    Asp部分: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyFiles ...

  9. FILE文件删除操作(删除指定文件夹下所有文件和文件夹包括子文件夹下所有文件和文件夹),就是删除所有

    2018-11-05  19:42:08开始写 选择 删除 1.FileUtils.java类 import java.io.File;//导入包 import java.util.List;//导入 ...

随机推荐

  1. C\C++中声明与定义的区别

    声明和定义是完全同的概念,声明是告诉编译器"这个函数或者变量可以在哪找到,它的模样像什么".而定义则是告诉编译器,"在这里建立变量或函数",并且为它们分配内存空 ...

  2. Asp,Net里的Form表单

    1.Form表单是页面与Web服务器交互过程中最重要的信息来源. 2.<form action="传到哪个页面的网站地址" method="post和get 两种方 ...

  3. XPath注入跟SQL注入差不多,只不过这里的数据库走的xml格式

    SQL注入这块不想细聊了,相信很多朋友都听到耳朵长茧,不外乎是提交含有SQL操作语句的信息给后端,后端如果没有做好过滤就执行该语句,攻击者自然可以随意操纵该站点的数据库. 比如有一个图书馆站点book ...

  4. PHP基础知识之对象复制

    对象的复制默认为浅复制 进行深复制的方法为:在类中定义魔法方法__clone(),类的对象复制时,会自动调用 __clone方法,在 __clone方法中可以进行各种复制对象的个性化 class My ...

  5. node(async原理)

    node中的async是用来实现同步操作的,提供包括map.Series等方法,本文不做赘述. 由于项目需要在浏览器端用了async.js,因此仔细看了下它的代码.原来,一直以为node是在服务端调用 ...

  6. ASP.Net请求处理机制初步探索之旅 - Part 3 管道

    开篇:上一篇我们了解了一个ASP.Net页面请求的核心处理入口,它经历了三个重要的入口,分别是:ISAPIRuntime.ProcessRequest().HttpRuntime.ProcessReq ...

  7. iOS开发系列--C语言之数组和字符串

    概览 数组在C语言中有着特殊的地位,它有很多特性,例如它的存储是连续的,数组的名称就是数组的地址等.而在C语言中是没有String类型的,那么如果要表示一个字符串,就必须使用字符数组.今天主要就介绍如 ...

  8. java中文乱码解决之道(八)-----解决URL中文乱码问题

    我们主要通过两种形式提交向服务器发送请求:URL.表单.而表单形式一般都不会出现乱码问题,乱码问题主要是在URL上面.通过前面几篇博客的介绍我们知道URL向服务器发送请求编码过程实在是实在太混乱了.不 ...

  9. Kinect for Windows SDK开发学习相关资源

    Kinect for Windows SDK(K4W)将Kinect的体感操作带到了平常的应用学习中,提供了一种不同于传统的鼠标,键盘及触摸的无接触的交互方式,在某种程度上实现了自然交互界面的理想,即 ...

  10. Tomcat搭建

    标签:Tomcat 概述 Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选. ...