android-fragments 列出Android中的所有Mp3文件

guicsvcw  于 2022-11-14  发布在  Android
关注(0)|答案(4)|浏览(108)

我正在开发的音乐播放器在Android中,但在阅读MP3文件卡住。这里是我的代码来读取所有的MP3文件。但它不返回任何文件从设备(虽然有一些文件,我使用adb复制)。我也希望它使用专辑列表,艺术家等,请在这方面的帮助。

final String MEDIA_PATH = Environment.getExternalStorageDirectory()+"";

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) {
    if (home.listFiles(new FileExtensionFilter())!=null) {

        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"));
    }
}
gk7wooem

gk7wooem1#

在这里我修改了getPlayList()方法。

ArrayList<HashMap<String,String>> getPlayList(String rootPath) {
            ArrayList<HashMap<String,String>> fileList = new ArrayList<>();

            try {
                File rootFolder = new File(rootPath);
                File[] files = rootFolder.listFiles(); //here you will get NPE if directory doesn't contains  any file,handle it like this.
                for (File file : files) {
                    if (file.isDirectory()) {
                        if (getPlayList(file.getAbsolutePath()) != null) {
                            fileList.addAll(getPlayList(file.getAbsolutePath()));
                        } else {
                            break;
                        }
                    } else if (file.getName().endsWith(".mp3")) {
                        HashMap<String, String> song = new HashMap<>();
                        song.put("file_path", file.getAbsolutePath());
                        song.put("file_name", file.getName());
                        fileList.add(song);
                    }
                }
                return fileList;
            } catch (Exception e) {
                return null;
            }
        }

您可以获得歌曲名称和歌曲路径,如下所示:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ArrayList<HashMap<String,String>> songList=getPlayList("/storage/sdcard1/");
        if(songList!=null){
        for(int i=0;i<songList.size();i++){
        String fileName=songList.get(i).get("file_name");
        String filePath=songList.get(i).get("file_path");
        //here you will get list of file name and file path that present in your device
        log.e("file details "," name ="+fileName +" path = "+filePath);
        }
        }
    }

**注意:**使用“/storage/sdcard 1/”从sdCard阅读文件,使用Environment.getExternalStorageDirectory().getAbsolutePath()从手机存储器读取文件

希望这对你有帮助。

dzhpxtsq

dzhpxtsq2#

希望你已经找到了你的答案,但可能这是更好的,如果你想尝试,这里是你的解决方案使用下面的代码从特定文件夹或所有文件中读取MP3文件,
首先创建1个模型类,如下所示,到列表中的GETSET文件。
AudioModel.class

public class AudioModel {

    String aPath;
    String aName;
    String aAlbum;
    String aArtist;

    public String getaPath() {
        return aPath;
    }

    public void setaPath(String aPath) {
        this.aPath = aPath;
    }

    public String getaName() {
        return aName;
    }

    public void setaName(String aName) {
        this.aName = aName;
    }

    public String getaAlbum() {
        return aAlbum;
    }

    public void setaAlbum(String aAlbum) {
        this.aAlbum = aAlbum;
    }

    public String getaArtist() {
        return aArtist;
    }

    public void setaArtist(String aArtist) {
        this.aArtist = aArtist;
    }
}

现在我们有我们的模型类,使用下面的代码来读取所有的MP3文件从您的文件夹或设备.
这将返回包含音乐的所有MP3文件的列表NAME, PATH, ARTIST, ALBUM。如果您想了解更多详细信息,请参阅documentation for Media.Store.Audio

public List<AudioModel> getAllAudioFromDevice(final Context context) {

        final List<AudioModel> tempAudioList = new ArrayList<>();

        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.ALBUM, MediaStore.Audio.ArtistColumns.ARTIST,};
        Cursor c = context.getContentResolver().query(uri, projection, MediaStore.Audio.Media.DATA + " like ? ", new String[]{"%yourFolderName%"}, null);

        if (c != null) {
            while (c.moveToNext()) {

                AudioModel audioModel = new AudioModel();
                String path = c.getString(0);
                String album = c.getString(1);
                String artist = c.getString(2);

                String name = path.substring(path.lastIndexOf("/") + 1);

                audioModel.setaName(name);
                audioModel.setaAlbum(album);
                audioModel.setaArtist(artist);
                audioModel.setaPath(path);

                Log.e("Name :" + name, " Album :" + album);
                Log.e("Path :" + path, " Artist :" + artist);

                tempAudioList.add(audioModel);
            }
            c.close();
        }

        return tempAudioList;
    }

若要读取特定文件夹中的文件,请使用以下查询(在查询中写入目标文件夹名称)

Cursor c = context.getContentResolver().query(uri,
                                          projection, 
                                          MediaStore.Audio.Media.DATA + " like ? ", 
                                          new String[]{"%yourFolderName%"}, // yourFolderName 
                                          null);

如果您想要装置上的所有档案,请使用此查询:

Cursor c = context.getContentResolver().query(uri,
                                          projection, 
                                          null, 
                                          null, 
                                          null);

不要忘记添加存储权限。

lsmd5eda

lsmd5eda3#

试试这个

String path;
File sdCardRoot = Environment.getExternalStorageDirectory();
File dir = new File(sdCardRoot.getAbsolutePath() + "/yourDirectory/");

if (dir.exists()) {

    if (dir.listFiles() != null) {
        for (File f : dir.listFiles()) {
            if (f.isFile())
                path = f.getName();

            if (path.contains(".mp3")) {
                yourArrayList.add(path);

            }
        }
    }
}
j9per5c4

j9per5c44#

此功能将为您提供设备存储中所有音频文件路径的列表

public ArrayList<String> getAllMusic(){
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String[] projection = {MediaStore.Audio.AudioColumns.DATA};
    ArrayList<String> songs_path = new ArrayList<>();
    Cursor c = context.getContentResolver().query(uri, projection, null,null,null);

    if (c != null) {
        while (c.moveToNext()) {

            String path = c.getString(0);
            songs_path.add(path);
        }
        c.close();
    }

    return songs_path;
}

ArrayList<String> allSongs = getAllMusic();

File song = new File(allSongs.get(0));

相关问题