before you say "Google it", I tried, found a few interesting articles, but nothing worked.
I need to convert a mp3 file from a website to a byte stream, that I can later save into a file locally.
Here is my code (most important parts):
Url url = new Url("someUrl");
URLConnection conn = url.openConnection();
byte[] result = inputStreamToByteArray(conn.getInputStream());
// .... some code here
byteArrayToFile(result, "tmp.mp3");
public byte[] inputStreamToByteArray(InputStream inStream){
InputStreamReader in = new InputStreamReader(inStream):
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int next = inStream.read();
while (next > -1){
baos.write(next);
next = in.read();
}
byte[] result = baos.toByteArray();
baos.flush();
in.close();
return result;
}
public void byteArrayToFile(byte[] byteArray, String outFilePath){
FileOutputStream fos = new FileOutputStream(outFilePath);
fos.write(byteArray);
fos.close()
}
The code compiles without errors. Connection to the url is valid. It sends the right response.
The problem is somewhere in the conversion. I also get the new file on disk, after byteArrayToFile(), with appropriate lenght, but I can't play it in any player. It says length 00:00 and will not play.
Btw. I'd like to avoid any 3rd party libs. But if nothing else works...