androidflutterandroid-intentflutter-method-channel

Android:Get audio metadata from URI


Aim: I have created a music player using flutter. And I want to play audio files from another app. For this purpose, I have used method channel for communication between flutter and Android.And I am getting the below URI from Intent.

Received URI:content://com.mi.android.globalFileexplorer.myprovider/external_files/song.mp3
Received PATH:/external_files/song.mp3

My Code

private MediaMetadataRetriever song details;
    private MetadataDetails[] songDetails;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        songDetails = new MediaMetadataRetriever();
        Intent intent = getIntent();

        new MethodChannel(AudioServicePlugin.getFlutterEngine(this).getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler(
                (call, result) -> {
                    if (call.method.equals("song")) {
                        if(intent != null && intent.getData() !=null) {
                            songDetails.setDataSource(intent.getData().getPath());
                            result.success(songDetails);
                        }
                        else {
                            result.success(null);
                        }
                    }
                });
    }

When I am fetching songDetails, I am getting the below error.

ERROR:setDataSource failed: status = 0xFFFFFFEA

I have tried below code.

FileInputStream file = new FileInputStream(intent.getData().getPath());
                               songDetails.setDataSource(file.getFD());

But it didn't work for me.

Can anyone guide me on how to do it?


Solution

  • Please check with following function

     private String generatePath(Uri uri, Context context){
            if ("content".equalsIgnoreCase(uri.getScheme())) {
                String[] projection = { "_data" };
                Cursor cursor = null;
    
                try {
                    cursor = context.getContentResolver().query(uri, projection, null, null, null);
                    int column_index = cursor.getColumnIndexOrThrow("_data");
                    if (cursor.moveToFirst()) {
                        return cursor.getString(column_index);
                    }
                } catch (Exception e) {
                    // Eat it
                }
            }
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
            return null;
        }
    

    Pass your file as

     Uri selectedFileUri = intent.getData();
     File filePath = new File(generatePath(selectedFileUri,this));