简体   繁体   中英

how to access mp3 files from sd card of a mobile device

I am trying to make a media player app but I am not able to access the music files from my mobile devise I have take the user permission also .how can I access the mp3 files.I tried to access the media file from a file from the SD Card with file name Download.But it is not working.Is there any way to access all the mp3 files from the android device?Here is my code

public class MainActivity extends ListActivity {
private static final String SD_PATH =new String("/Download/");
private List<String> songs =new ArrayList<String>();
private MediaPlayer mp =new MediaPlayer();
class Mp3Filter implements FilenameFilter{

    @Override
    public boolean accept(File dir, String filename) {
        return (filename.endsWith(".mp3"));
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    updatePlaylist();
    Button button =(Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp.stop();
        }
    });

}
protected void onListItemClick(ListView list,View view,int position,long id){
    try{
        mp.reset();
        mp.setDataSource(SD_PATH + songs.get(position));
        mp.prepare();
        mp.start();
    } catch (IOException e) {
        Log.v(getString(R.string.app_name),e.getMessage());
    }
}

private void updatePlaylist() {
   File home =new File(SD_PATH);
    if (home.listFiles(new Mp3Filter()).length > 0) {

        for(
                File file:home.listFiles(new Mp3Filter())
                ) {
            songs.add(file.getName());
        }
        ArrayAdapter<String>songlist =new ArrayAdapter<String>(this,R.layout.text,songs);
        setListAdapter(songlist);
    }
}

You are not pointing to the correct sd card directory . Your SD_PATH should look like -

String SD_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();

This is the external storage path of Downloads folder on the sd card for the device. You can append the particular file name to this path for your purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM