Convert mp3 file to a string.
To convert a mp3 file into a string, we first have to change it to byte array and then to the string.
The following function can convert the file to an array:
public String convert() {
String outputFile =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/recorded_audio.mp3";//It will save the mp3 file in phone's internal memory directory. byte[] bytearray = new byte[0];
try {
InputStream inputStream =
getContentResolver().openInputStream(Uri.fromFile(new File(outputFile)));
bytearray = new byte[inputStream.available()];
bytearray = toByteArray(inputStream);
Toast.makeText(this, "" + bytearray, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
return bytearray;
}
The Toast in the above function will not show you the exact byte array generated. If you want to see the byte array,
you use the following code:
String actualArray = Arrays.toString(bytearray);
This String will give you the actual array.
Reduce using Base64:
String reducedArray = Base64.encodeToString(bytearray,Base64.NO_WRAP);
This will reduce the string upto an extent. To reduce further you should use the function given below.
Reduce using hexString:
String lastString = bytesToHexString(bytearray);public static String bytesToHexString(byte[] in) {
final StringBuilder builder = new StringBuilder();
for(byte b : in) {
builder.append(String.format("%02x", b));
}
return builder.toString();
}
Convert HexString back to byte array:
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
Convert byte array to mp3 file:
Declare this line above onCreate function.
private MediaPlayer mediaPlayer = new MediaPlayer();
Use this function to get mp3 file back.
private void mp3File(byte[] bytearray) {
try {
File tempFile = File.createTempFile("mobile", "mp3", getCacheDir());
tempFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(bytearray);
fos.close();mediaPlayer.reset();
FileInputStream fis = new FileInputStream(tempFile);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException ex) {
String s = ex.toString();
ex.printStackTrace();
}
}
Get the full code: https://github.com/Himanshu-Choudhary-07/voicemail