Error sending audio saved in an app to whatsapp

2

The code I am using is:

String path= "android.resource://"+Principal.this.getPackageName()+"/raw/a.mp3"; 
Uri uri = Uri.parse(path);
Intent compartiraudio = new Intent(Intent.ACTION_SEND);
compartiraudio.setType("audio/*");
compartiraudio.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(compartiraudio, "Comparte un archivo de audio"));

I do not know what I'm doing wrong but the audio is not sent, the sharing menu is opened by whatsapp but by accepting it gives error.

    
asked by Isaac Ruiz 14.09.2017 в 18:36
source

1 answer

0

It is important to know that when trying to send a file through WhatsApp, it must be in the external storage directory, this applies to audio files, images, etc. If it is not in this location, we first need to make a copy of the file and save it in the external storage directory.

This is an example assuming you have an .mp3 file inside /raw/jorgesys_sound.mp3

Firstly, we make a copy of the file stored within /raw and then configure the intent to send this type of file through the Whatsapp application:

This is 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;
  }

Do not forget to define the permission:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
answered by 15.09.2017 в 18:26