how to get all all audio files from sd card android

后端 未结 4 1492
清酒与你
清酒与你 2020-12-30 16:35

I want to write a class which gets all the mp3 files from the whole sd card. But actually it only gets the audio files laying directly on the sd card. so it doesnt search tr

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 17:10

    final String MEDIA_PATH = Environment.getExternalStorageDirectory()
            .getPath() + "/";
    private ArrayList> songsList = new ArrayList>();
    private String mp3Pattern = ".mp3";
    
    // Constructor
    public SongsManager() {
    
    }
    
    /**
     * Function to read all mp3 files and store the details in
     * ArrayList
     * */
    public ArrayList> getPlayList() {
        System.out.println(MEDIA_PATH);
        if (MEDIA_PATH != null) {
            File home = new File(MEDIA_PATH);
            File[] listFiles = home.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    System.out.println(file.getAbsolutePath());
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }
                }
            }
        }
        // return songs list array
        return songsList;
    }
    
    private void scanDirectory(File directory) {
        if (directory != null) {
            File[] listFiles = directory.listFiles();
            if (listFiles != null && listFiles.length > 0) {
                for (File file : listFiles) {
                    if (file.isDirectory()) {
                        scanDirectory(file);
                    } else {
                        addSongToList(file);
                    }
    
                }
            }
        }
    }
    
    private void addSongToList(File song) {
        if (song.getName().endsWith(mp3Pattern)) {
            HashMap songMap = new HashMap();
            songMap.put("songTitle",
                    song.getName().substring(0, (song.getName().length() - 4)));
            songMap.put("songPath", song.getPath());
    
            // Adding each song to SongList
            songsList.add(songMap);
        }
    }
    

提交回复
热议问题