Search code examples
androidscoped-storagemp4parser

How to get file path of shared storage folder in Android 10 and above?


We are integrating scoped storage in our app, we are reading and writing video files in sahred storage e.g Environment.DIRECTORY_MOVIES folder (shared storage movies directory) it is working as expected but we need to write custom metadata in video to do that we are using org.mp4parser:isoparser. To read and write metadata, this library needs file object before scoped storage we can get absolute path using Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) now it's deprecated is there any other way to get the file path in scoped storage?

public static String readVideoMetadata(File videoFile) throws IOException {
    
        if (!videoFile.canRead()) {
            throw new IllegalStateException("No read permissions to file " + videoFile.getAbsolutePath());
        }
        if(!isImageFile(videoFile)) {
            try {
                IsoFile isoFile = new IsoFile(videoFile);
                if (null != Path.getPath(isoFile, "moov[0]/udta[0]/meta[0]/ilst/©cmt")) {
                    AppleCommentBox nam = Path.getPath(isoFile, "moov[0]/udta[0]/meta[0]/ilst/©cmt");
                    String xml = nam.getValue();
                    isoFile.close();
                    return xml;
                }
            } catch (OutOfMemoryError | Exception e) {
                e.printStackTrace();
            }
        }else{
            ExifInterface exifInterface=new ExifInterface(videoFile);
            String metaData= exifInterface.getAttribute(ExifInterface.TAG_USER_COMMENT);
            if(metaData!=null){
                return metaData;
            }
        }
    
        return "";
    }

Solution

  • Use FFMPEG Android library

    You can get file path from media URI using the below code

    Uri safUri = intent.getData();
    String inputVideoPath = FFmpegKitConfig.getSafParameterForRead(requireContext(), safUri);
    

    You can read media information using this below function

     MediaInformationSession mediaInformation = FFprobeKit.getMediaInformation("<file path or uri>");
    mediaInformation.getMediaInformation();