簡體   English   中英

如何訪問SD卡中所有子文件夾中的所有mp3文件?

[英]How to access all mp3 files from all the subfolders in the sdcard?

我正在嘗試制作一個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"));
    }
}  }

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

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    
}
}
}  
}  
}

更好地使用增強的for循環,如blackbelt @

從android中的文件夾中僅刪除.jpg文件

而不是刪除添加hahsmap的路徑

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM