Domanda

I am new to android programming so can anyone please help me to find all .mp3 files in my android device.

È stato utile?

Soluzione 2

Of course . you can . Code not tested.

File dir =new File(Environment.getExternalStorageDirectory());
if (dir.exists()&&dir.isDirectory()){
  File[] files=dir.listFiles(new FilenameFilter(){
   @Override
   public boolean accept(File dir,String name){
     return name.contains(".mp3");
  }
  });    
   }

Altri suggerimenti

You should use MediaStore. Here is an example code i'm using for something similar:

private static ArrayList<SongModel> LoadSongsFromCard() {
    ArrayList<SongModel> songs = new ArrayList<SongModel>();

    // Filter only mp3s, only those marked by the MediaStore to be music and longer than 1 minute
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"
            + " AND " + MediaStore.Audio.Media.MIME_TYPE + "= 'audio/mpeg'"
            + " AND " + MediaStore.Audio.Media.DURATION + " > 60000";

    final String[] projection = new String[] {
        MediaStore.Audio.Media._ID,             //0
        MediaStore.Audio.Media.TITLE,           //1
        MediaStore.Audio.Media.ARTIST,          //2
        MediaStore.Audio.Media.DATA,            //3
        MediaStore.Audio.Media.DISPLAY_NAME
    };

    final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
            + " COLLATE LOCALIZED ASC";

    Cursor cursor = null;

    try {
        // the uri of the table that we want to query
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; //getContentUriForPath("");
        // query the db
        cursor = _context.getContentResolver().query(uri,
                projection, selection, null, sortOrder);
        if (cursor != null) {
            cursor.moveToFirst();                       
            while (!cursor.isAfterLast()) { 
                //if (cursor.getString(3).contains("AwesomePlaylists")) {
                    SongModel GSC = new SongModel();
                    GSC.ID = cursor.getLong(0);
                    GSC.songTitle = cursor.getString(1);
                    GSC.songArtist = cursor.getString(2);
                    GSC.path = cursor.getString(3);

                    // This code assumes genre is stored in the first letter of the song file name
                    String genreCodeString = cursor.getString(4).substring(0, 1);
                    if (!genreCodeString.isEmpty()) {
                        try {
                            GSC.genre = Short.parseShort(genreCodeString);
                        } catch (NumberFormatException ex) {
                            Random r = new Random();
                            GSC.genre = (short) r.nextInt(4);
                        } finally {
                            songs.add(GSC);
                        }
                    }
                //}
                cursor.moveToNext();
            }
        }
    } catch (Exception ex) {

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return songs;
}

You can use recursive searching. Use this function with path of directory where you wanna start search .mp3 files (for example "/mnt/sdcard").

public Vector<String> mp3Files = new Vector<String>();

private void searchInDirectory(String directory)
{
    File dir = new File(directory);

    if(dir.canRead() && dir.exists() && dir.isDirectory())
    {
        String []filesInDirectory = dir.list();
        if(filesInDirectory != null)
        {
            for(int i=0; i<filesInDirectory.length; i++)
            {

                File file = new File(directory+"/"+filesInDirectory[i]);                    

                if(file.isFile() && file.getAbsolutePath().toLowerCase(Locale.getDefault()).endsWith(".mp3"))
                {
                    mp3Files.add(directory+"/"+filesInDirectory[i]);
                }

                else if(file.isDirectory() )
                {
                    searchInDirectory(file.getAbsolutePath());
                }

            }
        }
    }
}
public ArrayList<String> searchMP3File(ArrayList<String> aListFilePath, String rootPath) {

    File rootFile = new File(rootPath); 

    File[] aRootFileFilter = rootFile.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            if(pathname.getName().endsWith(".mp3"))
                return true;
            else 
                return false;
        }
    });

    if(aRootFileFilter != null && aRootFileFilter.length > 0) {
        for(int i = 0; i < aRootFileFilter.length; i++) {
            aListFilePath.add(aRootFileFilter[i].getPath());
        }
    }
    File[] aRootFile = rootFile.listFiles();
    for(int i = 0; i < aRootFile.length; i++) {
        if(aRootFile[i].isDirectory()) {
            ArrayList<String> aListSubFile = searchMP3File(aListFilePath, aRootFile[i].getPath());
            if(aListSubFile != null && aListSubFile.size() > 0)
                aListFilePath = aListSubFile;
        }
    }

    return aListFilePath;
}
private String[] videoExtensions;
videoExtensions = new String[2];
videoExtensions[0] = "mp3";
videoExtensions[1] = "3gp";

After this declaration in your onCreate() method, set below code in some method and call it. Do changes as per your need in my code.

try {

File file = new File("mnt/sdcard/DCIM/Camera");
            File[] listOfFiles = file.listFiles();

            videoArray = new ArrayList<HashMap<String, String>>();
            videoHashmap = new HashMap<String, String>();

            for (int i = videoIndex; i < listOfFiles.length; i++) {
                File files = listOfFiles[i];
                rowDataVideos = new HashMap<String, String>();
                for (String ext : videoExtensions) {
                    if (files.getName().endsWith("." + ext)) {
                        videoHashmap.put("Video", files.getAbsolutePath());
                        videoArray.add(videoHashmap);
                        fileSize = files.length();
                        fileSizeInMb += convertSize(fileSize, MB);

                        thumb = ThumbnailUtils.createVideoThumbnail(files.getAbsolutePath(), MediaStore.Images.Thumbnails.MINI_KIND);

                        if (thumb != null) {
                            createTempDirectory();
                            try {
                                FileOutputStream out = new FileOutputStream(audiofile);
                                thumb.compress(Bitmap.CompressFormat.PNG, 90, out);
                                out.flush();
                                out.close();

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        // Tue Apr 23 16:08:28 GMT+05:30 2013
                        lastModDate = new Date(files.lastModified()).toString();

                        dateTime = (dateToMilliSeconds(lastModDate) / 1000L);

                        rowDataVideos.put(VIDEOPATH, files.getAbsolutePath());
                        rowDataVideos.put(VIDEOSTATUS, "0");
                        rowDataVideos.put(VIDEOSIZEINMB, String.valueOf(fileSizeInMb));
                        rowDataVideos.put(VIDEODATE, String.valueOf(dateTime));

                        if (dateTime > (RESPONSE_TIMESTAMP_VIDEO / 1000L)) {
                            dataProvider.InsertRow(VIDEOS, rowDataVideos);
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top