1 year ago

#77187

test-img

Cosmin

How to save mp3 file stored on removable SD Card to MediaStore (Android Q)?

I have a function that should add a mp3 file to MediaStore, written to removable SD Card on Android Q. The file works just fine if I access it from File Explorer, but I can't see it on Music App (Samsung Music) in my case.

@NonNull
public Uri saveMediaToStore(@NonNull final Context context,File file,FileSong fileSong) throws IOException {

    final ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileSong.getName());
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, file.getCanonicalPath());

    }else {
        values.put(MediaStore.Audio.AudioColumns.DATA, file.getCanonicalPath());
    }


    final ContentResolver resolver = context.getContentResolver();
    Uri uri = null;

    try {
        final Uri contentUri;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            contentUri = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
        }else{
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
        uri = resolver.insert(contentUri, values);

        if (uri == null)
            throw new IOException("Failed to create new MediaStore record.");

        try (final OutputStream stream = resolver.openOutputStream(uri)) {
            if (stream == null)
                throw new IOException("Failed to open output stream.");

        }

        return uri;
    }
    catch (IOException e) {

        if (uri != null) {
            // Don't leave an orphan entry in the MediaStore
            resolver.delete(uri, null, null);
        }

        throw e;
    }
}

It seems to have added it. But when I look inside Samsung Music, it doesn't play, the path doesn't seem to be correct.

This is how MediaStore saved my path: https://imgur.com/6YI7s3a

This is how Android System saves the mp3 files if I download/copy a mp3 file inside the removable SD Card: https://imgur.com/w3hiR1H

Is it possible that Samsung Music can read those files and show them from SD Card and I as a developer can't?

Thank you in advance!

java

android

android-studio

file

storage

0 Answers

Your Answer

Accepted video resources