是否可以将音频mp3文件转换为字符串数据以便将数据发送到服务器, 和服务器将返回一个字符串数据到我的应用程序我想将该数据转换为MP3文件并播放音频。
我正在使用此代码将mp3文件转换为字符串数据
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;
}
我不知道如何从转换的strind数据中取回我的mp3文件。
如果可能的话怎么样?任何人帮助我。
或者此要求的任何其他解决方案告诉我:我想将音频和视频文件传递到服务器并从服务器返回以在应用程序中使用。
答案 0 :(得分:4)
使用Base64.encodeToString()试试这个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);
}
}
}
}
答案 1 :(得分:0)
Error:(49, 41) error: cannot find symbol method readFileToByteArray(File)
我认为您还没有在FileUtils中定义该方法,是吗?
我通过更改代码解决了这个问题,如下所示:
//byte[] bytes = FileUtils.readFileToByteArray(file);
byte[] bytes = new byte[(int)file.length()];