1

我正在尝试制作一个 mp3 播放器应用程序,当我从手机运行它时,它只会读取 SD 卡本身上存在的 MP3。它不会从卡中的子文件夹中读取任何 MP3。我希望它显示 SD 卡中存在的所有 MP3(包括子文件夹)。

public class SongsManager {
// SDCard Path
final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath());
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

// Constructor
public SongsManager(){

}

/**
 * Function to read all mp3 files from sdcard
 * and store the details in ArrayList
 * */
public ArrayList<HashMap<String, String>> getPlayList(){
    File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();
            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());

            // Adding each song to SongList
            songsList.add(song);
        }
    }
    // return songs list array
    return songsList;
}


/**
 * Class to filter files which are having .mp3 extension
 * */
class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3") || name.endsWith(".MP3"));
    }
}  }
4

2 回答 2

3

Android SDK 中有MusicRetriever示例。它使用ContentResolver

于 2013-08-28T14:33:26.983 回答
1
File home = new File(MEDIA_PATH);

然后

walkdir(home);

WalkDir 方法

public void walkdir(File dir) {
String Pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(Pattern)){
  //Do what ever u want
  // add the path to hash map    
}
}
}  
}  
}

正如 blackbelt @ 所建议的,更好地使用增强的 for 循环

从android中的文件夹中仅删除.jpg文件

而不是删除添加到hahsmap的路径

于 2013-06-20T10:09:23.327 回答