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"/>