Java base64 编码音频文件并作为字符串发送然后解码字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6448865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:02:56  来源:igfitidea点击:

base64 encode audio file and send as a String then decode the String

javaandroid

提问by ddavtian

I have been stuck on this issue for a few hours now trying to get it working. Basically what I am trying to do is the following. Base64 encode an audio file picked up from an sdcard on an Android device, Base64 encode it, convert it into a String and then decode the String using Base64 again and save the file back to sdcard. It all sounds fairly simple and works great when doing it using a text file. For example if I create a simple text file, call it dave.text and inject some text it in say "Hello Dave" or something similar it works great, but fails when I try doing the same with a binary file, audio in this example. Here's the code that I am using.

我已经在这个问题上停留了几个小时,现在试图让它工作。基本上我想做的是以下内容。Base64 对从 Android 设备上的 sdcard 中提取的音频文件进行编码,Base64 对其进行编码,将其转换为字符串,然后再次使用 Base64 解码字符串并将文件保存回 sdcard。这一切听起来都相当简单,而且在使用文本文件时效果很好。例如,如果我创建一个简单的文本文件,将其命名为 dave.text 并在其中注入一些文本,例如“Hello Dave”或类似的东西,它工作得很好,但是当我尝试对二进制文件(本例中的音频)执行相同操作时失败. 这是我正在使用的代码。

File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] FileBytes = FileUtils.readFileToByteArray(file);

byte[] encodedBytes = Base64.encode(FileBytes, 0);
String encodedString = new String(encodedBytes);                                        
Utilities.log("~~~~~~~~ Encoded: ", new String(encodedString));

byte[] decodedBytes = Base64.decode(encodedString, 0);
String decodedString = new String(decodedBytes);
Utilities.log("~~~~~~~~ Decoded: ", new String(decodedString));

try {
    File file2 = new File(Environment.getExternalStorageDirectory() + "/hello-5.wav");
    FileOutputStream os = new FileOutputStream(file2, true);
    os.write(decodedString.getBytes());
    os.flush();
    os.close();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

At this point if I try to save the file, it becomes corrupted. The audio file hello-5.wav is larger in size then the original and it doesn't play.

此时,如果我尝试保存文件,它会损坏。音频文件 hello-5.wav 比原始文件大,无法播放。

Any ideas what I am doing wrong here? If I try to save decodedBytes using os.write(decodedBytes) it works but not when converted to a String and getBytes() is used.

任何想法我在这里做错了什么?如果我尝试使用 os.write(decodedBytes) 保存 decodedBytes,它会起作用,但在转换为 String 并使用 getBytes() 时不起作用。

Any ideas? Thank You!

有任何想法吗?谢谢你!

采纳答案by Matt Ball

You're heavily mixing Strings and byte[]s. Don't do that. If you want to encode a byte[]to a String, use Base64.encodeToString(), instead of encoding to bytes and thencreating a string.

您正在大量混合Strings 和byte[]s。不要那样做。如果要将 a 编码byte[]为 a String,请使用Base64.encodeToString(), 而不是编码为字节然后创建字符串。

If I try to save decodedBytes using os.write(decodedBytes) it works but not when converted to a String and getBytes() is used.

如果我尝试使用 os.write(decodedBytes) 保存 decodedBytes,它会起作用,但在转换为 String 并使用 getBytes() 时不起作用。

Calling new String(byte[])does not do what you think it does.

调用new String(byte[])不会做你认为它会做的事情。

Likewise use Base64.decode(String, int)to decode the string.

同样用于Base64.decode(String, int)解码字符串。

Something like this (not tested):

像这样的东西(未测试):

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();
}


But why are you base64 encoding an audio file in the first place?

但是为什么首先要对音频文件进行 base64 编码?

回答by Faakhir

Decoding base64 string file to .m4a file format

将 base64 字符串文件解码为 .m4a 文件格式

try
{
    String audioDataString = "";
    BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.audioBase64File)));
    StringBuilder jsonBuilder = new StringBuilder();
    for (String line = null; (line = jsonReader.readLine()) != null; ) {
        jsonBuilder.append(line).append("");
    }
    audioDataString = jsonBuilder.toString();
    byte[] decoded = Base64.decode(audioDataString, Base64.DEFAULT);
    try {
        File file2 = new File(Environment.getExternalStorageDirectory() + "/faakhir_testAudio.m4a");
        FileOutputStream os = new FileOutputStream(file2, true);
        os.write(decoded);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
} catch(Exception e){
    e.printStackTrace();
}