我正在尝试从我的Android应用程序发送一个.wav文件到Django服务器。主要的问题是在服务器端经常出现这样的错误:波。错误:文件不以RIFF id开头
从客户端的角度来看,这是我转换测试的方法_音频.wav文件到字节[]
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字符串的方法:
^{pr2}$在服务器端我需要:
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,那么只需使用multipart/form数据请求在HTTP上发布二进制数据。在
如果出于某种原因,您坚持使用JSON,那么可以使用base64编码来实现这一点。在你的Android应用程序中,你需要对二进制数据进行base64编码。这将产生一个字符串。然后,可以将JSON格式的字符串发送到服务器。在服务器端,您将需要从JSON中获取这个base64编码的字符串,base64 decode,然后将其保存到文件中(或者您想对二进制数据执行的任何操作)。这里有一些小例子。在
客户端:
encodedString
是一个String
,然后将其添加到JSON中以发送到服务器。在服务器端:
^{pr2}$相关问题 更多 >
编程相关推荐