java mp3 inputstream to byte array?

后端 未结 1 623
我寻月下人不归
我寻月下人不归 2021-01-03 07:34

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

相关标签:
1条回答
  • 2021-01-03 08:03

    (The code you've presented wouldn't compile without errors, by the way. You haven't got required exception handling, and inputStream should be InputStream, just for starters.)

    This is the problem:

    InputStreamReader in = new InputStreamReader(inStream):
    

    You're trying to read from a binary stream, and convert it into text. It isn't text. You shouldn't be using anything to do with "Reader" or "Writer" for binary data like an MP3 file.

    Here's what your inputStreamToByteArray method should look like (or use Guava and its ByteStreams.toByteArray method):

    public byte[] inputStreamToByteArray(InputStream inStream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = inStream.read(buffer)) > 0) {
            baos.write(buffer, 0, bytesRead);
        }
        return baos.toByteArray();
    }
    

    Note that I've left it for the caller to clean up the input stream. Typically whoever fetches the stream also closes it - it would be slightly odd for a method like this to close it itself, IMO. You could do so if you wanted to, but probably in a finally block so you'd know that it would always be closed even if an exception was thrown.

    Note that your "writing" code later on won't close the file if there's an exception, either. You should get in the habit of always closing streams in finally blocks.

    0 讨论(0)
提交回复
热议问题