简体   繁体   中英

How to get all the audio file using mediastore

I am trying to get all the media files from the device (Internal and SDcard).Till now I am able to get all the media files from a fixed folder of SD Card .I have gone through most of the web pages on mediastore .And i am able to get the media info.But how can I get all the audio files from the device any example will be helpful. I tried this way ` public class SongDto {

public long songId;
public String songTitle;
public String songArtist;
public String path;
public short genre;
public long duration;
public String album;
public Bitmap albumArt;

public String toString() {
return String.format("songId: %d, Title: %s, Artist: %s, Path: %s, Genere: %d, Duration %s",
        songId, songTitle, songArtist, path, genre, duration);
}

and getting these value in another class name

public class Utils {
private Context _context;

// constructor
public Utils(Context context) {
    this._context = context;
}
public static ArrayList<SongDto> getMusicInfos(Context context) {

    ArrayList<SongDto> musicInfos = new ArrayList<SongDto>();

and now I am trying to get the the songTitle in another class

private ArrayList<SongDto> musicInfos;
private Utils utils;
private ArrayList<String> songPaths = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    utils = new Utils(this);
    songPaths = utils. getMusicInfos(songTitle);
}

private void update(){
    ArrayAdapter<String> list=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,musicInfos.add(songTitle) );
}
}

How I can get only the desired array like array of songId ,songArtist,song duration.And where I am doing wrong .How to set the getMusicInfos method `

You can try this

 ArrayList audio=new ArrayList();
 Cursor c=getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media.DISPLAY_NAME}, null, null, null);


while(c.moveToNext())
 {
String name=c.getString(c.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
audio.add(name);

 }

and similarly you can also get the internel storage audio files by specifying INTERNEL_CONTENT_URI

I used this code to get all song data

public static ArrayList<SongDto> getMusicInfos(Context context) {

    ArrayList<SongDto> musicInfos = new ArrayList<SongDto>();

    Cursor cursor = context.getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
            MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
    if (cursor == null) {
        return null;
    }


    for (int i = 0; i < cursor.getCount(); i++) {
        cursor.moveToNext();


        int isMusic = cursor.getInt(cursor
                .getColumnIndex(MediaStore.Audio.Media.IS_MUSIC)); 

        if (isMusic != 0) {
            SongDto music = new SongDto();


            music.path = cursor.getString(cursor
                    .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));

            if (!new File(music.path).exists()) {
                continue;
            }


            music.songId = cursor.getLong(cursor
                    .getColumnIndexOrThrow(MediaStore.Audio.Media._ID));

            music.songTitle = cursor.getString(cursor
                    .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));


            music.songTitle = cursor.getString(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));


            music.album = cursor.getString(cursor
                    .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));


            music.songArtist = cursor.getString(cursor
                    .getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));

            music.duration = cursor
                    .getLong(cursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(music.path);
            music.albumArt = getBitmap(mmr.getEmbeddedPicture());
            mmr.release();

            musicInfos.add(music);
        }
    }

    return musicInfos;
}

and use this as data object

public class SongDto {

public long songId;
public String songTitle;
public String songArtist;
public String path;
public short genre;
public long duration;
public String album;
public Bitmap albumArt;

public String toString() {
    return String.format("songId: %d, Title: %s, Artist: %s, Path: %s, Genere: %d, Duration %s",
            songId, songTitle, songArtist, path, genre, duration);
}
}

AbumArt might come as null

To fetch song id as list

 String[] columns = { MediaStore.Audio.Media._ID };
    cursor = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,columns, null, null, null);

and get the data from cursor. To get both internal and external storage songs list, as of now I don't have a solution.

The following code fetches all the mp3 files in the phone (including the audio files downloaded from messangers, recorded files etc) :

private fun getAllMusics(): List<String> {
    val result = mutableListOf<String>()

    val cursor = contentResolver.query(
        MediaStore.Files.getContentUri("external"),
        arrayOf(MediaStore.Files.FileColumns.DATA),
        "${MediaStore.Files.FileColumns.MIME_TYPE} = ?",
        arrayOf(MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp3")),
        MediaStore.Files.FileColumns.DATE_ADDED
    )

    cursor?.let {
        if (cursor.moveToFirst()) {
            while (cursor.moveToNext()) {
                result.add(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)) ?: "--")
            }
        }
    }

    return result
}

You can get other audio files (like WAV, WMA etc) by modifying the selection and selection args parameters.

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