Android Studio music player cant read from sdcard, only internal memory

后端 未结 1 1000
隐瞒了意图╮
隐瞒了意图╮ 2021-02-11 00:15

I apologize if this turns out to be a stupid question, it might turn out as a quick fix but I just cant figure it out. I\'m building a music player in android studio and none of

1条回答
  •  花落未央
    2021-02-11 00:55

    Use this method to get the list of filePath from your device

     ArrayList findSongs(String rootPath) {
        ArrayList 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 (findSongs(file.getAbsolutePath()) != null) {
                        fileList.addAll(findSongs(file.getAbsolutePath()));
                    } else {
                        break;
                    }
             } else if (file.getName().endsWith(".mp3")) {
                 fileList.add(file.getAbsolutePath());
             }
        }
        return fileList;
        }catch(Exception e){
           return null;
        }
    }
    

    but you need to get files from sdCard, for that pass "/storage/sdcard1/" as the parameter for findSongs(String path) method like this:

    onCreate(Bundle svaeInstance){
     ........
     ........
      if(findSongs("/storage/sdcard1/")!=null){
        ArrayList listOfFilePath=findSongs("/storage/sdcard1/"); // here you will get all the files path which contains .mp3 at the end.
     //do the remaining stuff
      }else { Toast.makeText(this, "sdCard not available", Toast.LENGTH_SHORT).show();
      }
     ......
    }
    

    Note: use "/storage/sdcard1/" for reading files from sdCard and use Environment.getExternalStorageDirectory().getAbsolutePath() for reading files from phone memory.

    Hope this will help you.

    0 讨论(0)
提交回复
热议问题