Is it possible to convert an audio mp3 file to a string data for sending data to the server, and server will return a string data to my app i want to convert that data to mp3 file and play audio.
I am using this code to convert mp3 file to string data
public static String readFileAsString(String filePath) throws java.io.IOException {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line, results = "";
while( ( line = reader.readLine() ) != null)
{
results += line;
}
reader.close();
return results;
}
i don't know how to get back my mp3 file from converted strind data.
If possible then how ? anybody help me.
Or any other solution for this requirement tell me: i want to pass audio and video files to server and get back from the server to use in app.
use Base64.encodeToString() try this http://developer.android.com/reference/android/util/Base64.html#encodeToString%28byte%5B%5D,%20int%29
File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
Utilities.log("~~~~~~~~ Encoded: ", encoded);
byte[] decoded = Base64.decode(encoded, 0);
Utilities.log("~~~~~~~~ Decoded: ", Arrays.toString(decoded));
try
{
File file2 = new File(Environment.getExternalStorageDirectory() + "/hello-5.wav");
FileOutputStream os = new FileOutputStream(file2, true);
os.write(decoded);
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}
public class FileUtils {
/**
* Instances should NOT be constructed in standard programming.
*/
public FileUtils() { }
/**
* The number of bytes in a kilobyte.
*/
public static final long ONE_KB = 1024;
/**
* The number of bytes in a megabyte.
*/
public static final long ONE_MB = ONE_KB * ONE_KB;
/**
* The number of bytes in a gigabyte.
*/
public static final long ONE_GB = ONE_KB * ONE_MB;
public static String readFileToString(
File file, String encoding) throws IOException {
InputStream in = new java.io.FileInputStream(file);
try {
return IOUtils.toString(in, encoding);
} finally {
IOUtils.closeQuietly(in);
}
}
}
}
Error:(49, 41) error: cannot find symbol method readFileToByteArray(File)
i think you have not defined that method in FileUtils, did you ?
i have resolved this issue by changing the code as follows:
//byte[] bytes = FileUtils.readFileToByteArray(file);
byte[] bytes = new byte[(int)file.length()];
来源:https://stackoverflow.com/questions/13819097/how-to-convert-audio-mp3-file-to-string-and-vice-versa