Reputation: 15
I'm trying to save an audio file to send it to whatsapp, but i am unable to save it on external storage. I am not getting where am I making mistakes.
I am using this code:
FileOutputStream outputStream;
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES), "FUNG");
if (!file.mkdirs()) {}
try {
outputStream = new FileOutputStream(file);
outputStream.write(R.raw.badum2);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES) + "/FUNG/badum2.m4a");
shareIntent.setType("audio/m4a");
shareIntent.setPackage("com.whatsapp");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(shareIntent);
When the file is sent to WhatsApp, it shows error like:
"fail to share, please try again"
I don't see the audio file in directory, so I guess the error is that I am making some mistakes in saving audio files on external storage.
Please help me in solving this.
Upvotes: 0
Views: 1294
Reputation: 571
I see multiple problems:
(1) if (!file.mkdirs()) {}
creates a directory at the path of file, later you use that directory to open an output stream, which of course does not work.
Solution:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES), "FUNG/badum2.m4a"); // assumed target file
if (!file.getParentFile().mkdirs() && !file.getParentFile().isDirectory()) {
// Abort! Directory could not be created!
}
(2) outputStream.write(R.raw.badum2);
will write the int value referring
to your resource, not the resource itself.
Solution:
Use InputStream in = ctx.getResources().openRawResource(R.raw.badum2);
where ctx is a Context instance (e.g. your Activity) and write its content to the file.
try {
outputStream = new FileOutputStream(file);
try {
InputStream in = ctx.getResources().openRawResource(R.raw.badum2);
byte[] buffer = new byte[4096];
int read;
while ((read = in.read(buffer, 0, buffer.length) >= 0) {
outputStream.write(buffer, 0, read);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 1