eclipse 如何从sd卡android获取所有音频文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19680563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 21:17:54  来源:igfitidea点击:

how to get all all audio files from sd card android

androideclipseaudiopathmediastore

提问by vinzzenzz

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 trough sub folders.I'd like to use Mediastore but i dont get it to an arraylist. Maybe you can help me, thanks a lot and sorry for beeing a noob ;) vinzenz

我想编写一个从整个 SD 卡中获取所有 mp3 文件的类。但实际上它只获取直接放在 SD 卡上的音频文件。所以它不会搜索低谷子文件夹。我想使用 Mediastore,但我没有把它放到一个数组列表中。也许你可以帮助我,非常感谢,很抱歉成为菜鸟 ;) vinzenz

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;

import de.me.musicplayer.SongsManager.FileExtensionFilter;

import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;




public class SongsManager {

final String MEDIA_PATH = new String("/sdcard/");
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"));
    }
}
}

回答by Basbous

final String MEDIA_PATH = Environment.getExternalStorageDirectory()
        .getPath() + "/";
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private String mp3Pattern = ".mp3";

// Constructor
public SongsManager() {

}

/**
 * Function to read all mp3 files and store the details in
 * ArrayList
 * */
public ArrayList<HashMap<String, String>> 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<String, String> songMap = new HashMap<String, String>();
        songMap.put("songTitle",
                song.getName().substring(0, (song.getName().length() - 4)));
        songMap.put("songPath", song.getPath());

        // Adding each song to SongList
        songsList.add(songMap);
    }
}

回答by Vivek Pratap Singh

You can also fetch Using ContentResolver class I have done like this and it's working fine

你也可以使用 ContentResolver 类来获取我已经这样做了并且它工作正常

public void getSongListFromStorage() {
        //retrieve song info
  ContentResolver musicResolver = getContentResolver();
  Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

  if (musicCursor != null && musicCursor.moveToFirst()) {
  //get columns
  int titleColumn = musicCursor.getColumnIndex
                    (android.provider.MediaStore.Audio.Media.TITLE);
  int idColumn = musicCursor.getColumnIndex
                    (android.provider.MediaStore.Audio.Media._ID);
 int artistColumn = musicCursor.getColumnIndex
                    (android.provider.MediaStore.Audio.Media.ARTIST);
 //add songs to list
  do {
      long thisId = musicCursor.getLong(idColumn);
      String thisTitle = musicCursor.getString(titleColumn);
      String thisArtist = musicCursor.getString(artistColumn);
      songList.add(new Song(thisId, thisTitle, thisArtist));
      } while (musicCursor.moveToNext());
   }
 }

回答by Dharmendra K. Jain

This code will give you an arrayList of hash map which content the song title as well as song absolute path

此代码将为您提供一个包含歌曲标题和歌曲绝对路径的哈希映射数组列表

public ArrayList<HashMap<String, String>> getAudioList() {

    ArrayList<HashMap<String, String>> mSongsList = new ArrayList<HashMap<String, String>>();
    Cursor mCursor = getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Audio.Media.DISPLAY_NAME,
                    MediaStore.Audio.Media.DATA }, null, null, null);

    int count = mCursor.getCount();
    System.out.println("total no of songs are=" + count);
    HashMap<String, String> songMap;
    while (mCursor.moveToNext()) {
        songMap = new HashMap<String, String>();
        songMap.put("songTitle",mCursor.getString(mCursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)));
        songMap.put("songPath", mCursor.getString(mCursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
        mSongsList.add(songMap);
    }
    mCursor.close();
    return mSongsList;
}

回答by Bhanu Sharma

private void getallaudio()
    {
        String[] STAR = { "*" };
        controller.audioWrapper.clear();
        Cursor audioCursor = ((Activity) cntx).managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
        if (audioCursor != null) 
        {
            if (audioCursor.moveToFirst()) 
            {
                do 
                {
                    String path = audioCursor.getString(audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                    audioWrapper.add(new MediaWrapper(new File(path).getName(), path, "Audio",false));
//                    Log.i("Audio Path",path);
                }while (audioCursor.moveToNext());

            }
//            audioCursor.close();
        }
    }