How to share audio from raw internal directory?

Asked

Viewed 241 times

0

I have several audios stored in the app’s raw directory and would like to share with other apps, such as Whatsapp, but I found very confusing the documentation on how to set up File Provider

Androidmanifest.xml

 <provider
        android:name="android.support.v4.content.FileProvider"
        android:grantUriPermissions="true"
        android:exported="false"
        android:authorities="com.namepackage.fileprovider">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths"/>

    </provider>

Here comes the filepaths configuration that I have doubts how to solve, it’s like this: filepaths.xml

 <paths>
<files-path name="files" path="/" />

And the Intent itself:

  File imagePath = new File(context.getFilesDir(), "nomearquivo.mp3");
        Uri uri = FileProvider.getUriForFile(context,"com.namepackege.fileprovider",
                imagePath);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.putExtra(Intent.EXTRA_STREAM, uri);
        share.setType("audio/mp3");
        share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(share);

But that code doesn’t work, I’d like to change it so it works

  • It seems to me that it is not possible just by using Fileprovider, according to Commonsware on this reply, you have two alternatives: 1) Create a Fileprovider that accesses the raw folder’s Resources. 2) Use Streamprovider that implements this logic: https://github.com/commonsguy/cwac-provider

1 answer

0

A way, among others, to do this, is to save the file first on the device before sending. See a simple method:

public Uri shareItemRaw(int songInRawId, String songOutFile) {
    File dest = Environment.getExternalStorageDirectory();
    InputStream in = getResources().openRawResource(songInRawId);

    try {
        OutputStream out = new FileOutputStream(new File(dest, songOutFile));
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (Exception ignored) {
    }

    return Uri.parse(
        Environment.getExternalStorageDirectory().toString() + "/" + songOutFile);
}

So you create your intent in this way:

Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, shareItemRaw(R.raw.song, "song.mp3")); 
share.setType("audio/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(share);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.