12

I'm trying to make a button for sharing an audio file. This is not working. First I tried to send the file right from my raw folder without copying it to the card of the phone. That didn't solve my problem. The second thing I tried, is saving the file to the phone and then share it. The part that saves the file to the phone works now, but when I try to share the audio file to another device all the compatible apps crash (Whatsapp, Gmail, etc).

This is my code:

    String sharePath = Environment.getExternalStorageDirectory().getPath()
    + "/Soundboard/Ringtones/custom_ringtone.ogg";
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("audio/*");
    share.putExtra(Intent.EXTRA_STREAM, sharePath);
    startActivity(Intent.createChooser(share, "Share Sound File"));

By the way, the audio file is a .ogg file. I hope that those apps work with that type of files. If not I should convert it to .mp3.

Thanks in advance!

Wannabe
  • 727
  • 1
  • 6
  • 21

10 Answers10

27

Oké, found out what I did wrong. For people who have the same problem, this is how I solved it:

I forgot to parse the String to an uri. Thats the only line of code I had to add. Uri uri = Uri.parse(sharePath);

Here is the full rest:

    String sharePath = Environment.getExternalStorageDirectory().getPath()
            + "/Soundboard/Ringtones/custom_ringtone.ogg";
    Uri uri = Uri.parse(sharePath);
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("audio/*");
    share.putExtra(Intent.EXTRA_STREAM, uri);
    startActivity(Intent.createChooser(share, "Share Sound File"));

Also do not forget to add permission WRITE_EXTERNAL_STORAGE otherwise you'll get an error while running your application.

Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
Wannabe
  • 727
  • 1
  • 6
  • 21
  • Nice answer, it usefull to me. – Nikunjkumar Kapupara Aug 16 '17 at 09:45
  • I can share the audio file using similar code in my app, but when I have image + text + audio to be shared together in one button click, on whatsapp it works fine, but on gmail it does not attach the audio file and the image, just the text is sent. Any pointers on what might be the issue? – Sanjyot Shah Sep 10 '18 at 14:07
  • @SanjyotShah Can you please tell me how did you send audio+text in single intent to WhatsApp? Looks like the WhatsApp is not reading the extra text if it's with the audio file. – Srinivasan Sep 05 '19 at 10:00
4

This is my way.

Uri uri = Uri.parse("file://" + sharePath);
Pang
  • 9,564
  • 146
  • 81
  • 122
Chanh
  • 433
  • 3
  • 12
2

Try this code. It's worked for me:

    public class MainActivity extends AppCompatActivity {
    private File mAudioFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //TODO Should handle Allow and Deny and include checkpermission
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                1);

        //Save Audio in Storage as File
        saveAudio();

        findViewById(R.id.btn_share_audio).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                shareAudioFile();

            }
        });

    }


    private void shareAudioFile() {

        String authorities = BuildConfig.APPLICATION_ID + ".fileprovider";
        Uri    path        = FileProvider.getUriForFile(this, authorities, mAudioFile);

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_STREAM, path);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setType("audio/mp3");//Replace with audio/* to choose other extensions
        startActivity(Intent.createChooser(intent, "Share Audio"));

    }

    private void saveAudio() {

        String downloadPath = Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_MUSIC)).getAbsolutePath() + "/";

        InputStream inputStream = getResources().openRawResource(R.raw.music);
        mAudioFile = new File(downloadPath + "audio.mp3");
        copyInputStreamToFile(inputStream, mAudioFile);
    }

    /**
     * @param inputStream raw/music
     * @param file        Storage path
     */
    private void copyInputStreamToFile(InputStream inputStream, File file) {
        OutputStream out = null;

        try {
            out = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int    len;
            while ((len = inputStream.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Ensure that the InputStreams are closed even if there's an exception.
            try {
                if (out != null) {
                    out.close();
                }
                // If you want to close the "in" InputStream yourself then remove this
                // from here but ensure that you close it yourself eventually.
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
DoctorWho
  • 1,044
  • 11
  • 34
1

Below code worked for me

    SoundFiles soundFiles=.....
    String FullFilePath=soundFiles.getPath();
    Uri uri = Uri.fromFile(new File(FullFilePath));
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("audio/*");
    share.putExtra(Intent.EXTRA_STREAM, uri);
    startActivity(Intent.createChooser(share, "Share Sound File"));
Abhishek Kumar
  • 111
  • 1
  • 7
0

change this line and it will support whatsapp and other apps:

share.setType("audio/mp3");

because whatsapp does not support ("audio/*"); or ("*/*");

Shubham
  • 1,205
  • 1
  • 12
  • 15
0

Send Audio file via WhatsApp:

We have to remember that the media file to share via WhatsApp must be stored in External Storage Directory, in this case you are going to send a file stored in /raw folder, so we have to make a copy and then make the intent to send this file via Whatsapp:

This is an example supposing to have a file /raw/jorgesys_sound.mp3

enter image description here

This are the methods to use

  private void sendWhatsAppAudio(){
        try {
           //Copy file to external ExternalStorage.
           String mediaPath = copyFiletoExternalStorage(R.raw.jorgesys_sound, "jorgesys_sound.mp3");

           Intent shareMedia = new Intent(Intent.ACTION_SEND);
            //set WhatsApp application.
            shareMedia.setPackage("com.whatsapp");
            shareMedia.setType("audio/*");
            //set path of media file in ExternalStorage.
            shareMedia.putExtra(Intent.EXTRA_STREAM, Uri.parse(mediaPath));
        startActivity(Intent.createChooser(shareMedia, "Compartiendo archivo."));
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Whatsapp no se encuentra instalado", Toast.LENGTH_LONG).show();
        }
    }

    private String copyFiletoExternalStorage(int resourceId, String resourceName){
        String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/" + resourceName;
        try{
        InputStream in = getResources().openRawResource(resourceId);
        FileOutputStream out = null;
        out = new FileOutputStream(pathSDCard);
        byte[] buff = new byte[1024];
        int read = 0;
        try {
            while ((read = in.read(buff)) > 0) {
                    out.write(buff, 0, read);
            }
        } finally {
            in.close();
            out.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return  pathSDCard;
  }

With this methods you can send any file via WhatsApp.

enter image description here

Remember to have the permission:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Community
  • 1
  • 1
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0
Intent intent = new Intent(); 
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new
File(Environment.getExternalStorageDirectory().getPath() + 
"/myMusic/Sound.mp3"))); 
intent.setType("audio/*");
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
startActivity(Intent.createChooser(intent, "Share Audio Abd Alazez..."));
ABD ALAZEZ
  • 21
  • 2
  • 2
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Dharman Jan 23 '20 at 21:33
0

I think I have a very common and easiest way to share all types of files.

  • It is very simple. Perform the below step.

    • Get file URI using the media scanner class and use it to share files.
    • Create sender Intent.
    • Add mime type of file and add file URI to share data.
    • Lastly create an intent chooser to select apps and start an activity with that intent
  • I have one example below to better understands.

    public void shareFile(String filePath) {
      if (filePath != null && !filePath.isEmpty()) {
          MediaScannerConnection.scanFile(activity, new String[]{filePath}, null,
                  (path, uri) -> {
                      Log.i(TAG, "onScanCompleted: path :- " + path + " uri :- " + uri);
                      if (uri != null) {
                          try {
                              Intent shareIntent = new Intent(Intent.ACTION_SEND); // create action send
                              shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                              shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    
                              // create mime type of file from file uri
                              String mimeType;
                              if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
                                  ContentResolver cr = activity.getContentResolver();
                                  mimeType = cr.getType(uri);
                              } else {
                                  String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                                          .toString());
                                  mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                                          fileExtension.toLowerCase());
                              }
    
                              // shareIntent.setPackage(""); // you can specify app package name here to share file that app only
                              shareIntent.setDataAndType(uri, mimeType);
                              shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                              startActivity(Intent.createChooser(shareIntent, "Share File"));
                          } catch (Throwable throwable) {
                              Log.i(TAG, "shareSong: error :- " + throwable.getMessage());
                          }
                      }
                  });
      } else {
          Log.i(TAG, "shareSong: currentMusic NULL");
      }
    }
    
  • You have passed only the file path to this method it will handle all other things.

  • Note :- You have READ_EXTERNAL_STORAGE permission before calling this method.

I hope it will useful to all our community.

Bhaven Shah
  • 692
  • 1
  • 5
  • 18
0

This solution works on Android 13 to share files from internal storage like /data/data/com.your.package/files/audio In this case your file you want to share is: /data/data/com.your.package/files/audio/myfile.aac

It also works with subfolders. Hope this solution may help.

   String fileName = "myfile.aac";
   String file_path = mContext.getApplicationContext().getFilesDir().getPath();
   File file = new File(file_path);
   set_ChildrenFolder("audio/", mContext);
   String file_name = file + separator + "audio" + separator + fileName;

   //https://stackoverflow.com/a/68826080/11564663
   File mAudioFile = new File(file_name);
   String authorities = BuildConfig.APPLICATION_ID + ".fileprovider";
   Uri path = FileProvider.getUriForFile(mContext, authorities, mAudioFile);

   Intent intent = new Intent();
   intent.setAction(Intent.ACTION_SEND);
   intent.putExtra(Intent.EXTRA_STREAM, path);
   intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
   intent.setType("audio/mp3");//Replace with audio/* to choose other extensions
   //intent.setType("audio/*");//Replace with audio/* to choose other extensions
   mContext.startActivity(Intent.createChooser(intent, "Share Audio"));

and here is the set_ChildrenFolder()

   
    public static File set_ChildrenFolder(String path, Context mContext) {
        File dir = mContext.getFilesDir();
        List<String> dirs = new ArrayList<String>(Arrays.asList(path.split("/")));
        for (int i = 0; i < dirs.size(); ++i) {
            dir = new File(dir, dirs.get(i)); //Getting a file within the dir.
            if (!dir.exists()) {
                dir.mkdir();
            }
        }
        return dir;
    }
adatadoc
  • 169
  • 1
  • 7
-2

I'm using:

final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/mp3");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/breakfast.mp3"));
startActivity(Intent.createChooser(shareIntent, "Condividi attraverso:"));

but gmail say "Can't attach empty file"

Ichigo Kurosaki
  • 3,765
  • 8
  • 41
  • 56