简体   繁体   中英

How can I get information about the audio file that was selected by the user? (using SAF and MediaStore)

I can't understand how to request data about a file (that was selected by the user) from MediaStore .

1) I open file picker like this

public static void launchPicker(Fragment f) {
        Intent pickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        pickerIntent.setType("audio/mpeg");
        pickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        pickerIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        f.startActivityForResult(pickerIntent, REQUEST_CODE);
    }

2) get the data from the intent

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            //multiselection only
            ClipData clipData = data.getClipData();
            if (clipData != null) {
                List<Uri> results = new ArrayList<>();
                for(int i = 0; i < clipData.getItemCount(); i++) {
                    Uri uri = clipData.getItemAt(i).getUri();
                    if (uri != null) {
                        results.add(uri);
                    }
                }
                //TODO process result
            }
        }
    }

3) Now I have my list of DocumentUris. What should be my next step?

MediaSoter can convert mediaUri to documentUri via Mediastore.getDocumentUri() , but I couldn't find a way to convert documentUri to mediaUri.

I would like to get these fields from MediaStore: MediaStore.Audio.Media._ID , ALBUM_ID , ARTIST_ID .

I do that this way:

Uri documentUri = DocumentsContract.buildDocumentUriUsingTree(mUri,
                    documentId);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(mContext,documentUri);
String albumName = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); 
String album = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
String title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
String track = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER);
String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
String year = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR);

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