【发布时间】:2016-02-01 02:35:08
【问题描述】:
我正在尝试将 .wav 文件从我的 Android 应用程序发送到 Django 服务器。主要问题是在服务器端不断收到这个错误:wave.Error: file does not start with RIFF id
从客户端的角度来看,这是我将 test_audio.wav 文件转换为 byte[]
的方式HashMap<String, String> postParams = new HashMap<>();
InputStream inStream = testPronunciationView.getContext().getResources().openRawResource(R.raw.test_audio);
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = new BufferedInputStream(inStream);
int read;
byte[] buff = new byte[1024];
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
out.flush();
byte[] fileAudioByte = out.toByteArray();
// two options to transform in a string
// 1st option
String decoded = new String(fileAudioByte, "UTF-8");
// 2nd option
String decoded = toJSON(fileAudioByte);
// decoded = either one of above
postDataParams.put("Audio", decoded)
// ....
// prepare a POST request here to send to the server
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
编辑: 创建 JSON 字符串的方法:
public static String toJSON(Object object) throws JSONException, IllegalAccessException
{
String str = "";
Class c = object.getClass();
JSONObject jsonObject = new JSONObject();
for (Field field : c.getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
String value = String.valueOf(field.get(object));
jsonObject.put(name, value);
}
System.out.println(jsonObject.toString());
return jsonObject.toString();
}
在服务器端我做:
audiofile_string = data['FileAudio']
audiofile_byte = list(bytearray(audiofile_string, 'utf8'))
temp_audiofile = tempfile.NamedTemporaryFile(suffix='.wav')
with open(temp_audiofile.name, 'wb') as output:
output.write(''.join(str(v) for v in audiofile_byte))
# The following line throws the error
f = wave.open(temp_audiofile.name, 'r') # wave.py library
所以我认为我在转换或通话后做错了什么。有什么建议吗?谢谢
【问题讨论】:
-
我写了一个答案但删除了它,因为我没有足够仔细地查看您的代码。看起来您甚至没有使用 JSON,但 JSON 无法处理这样的原始二进制数据。如果您使用的是 JSON,一种选择是在将二进制数据放入 JSON 之前对其进行 base64 编码。
-
@mittmemo 你是对的。我添加了用于将 Object 转换为 JSON 字符串的方法。
标签: android python json django audio