How to convert byte[] to mp3

Asked

Viewed 235 times

0

I’m writing an app where I have a list of byte[] and need to create files .mp3 from these byte vectors. When prompted, the app zips all these files into one file .zip, but later the player is not able to play any of these audios. The byte[] originates from a openStream(), where it is transformed into a byte array so that the app can have all audios "in memory", so that only then all are transformed into a file.

Creates archive

 private File createFile(String name, byte[] data) {
        try {
            FileOutputStream out = getContext().openFileOutput(name, Context.MODE_PRIVATE);
                             out.write(data);
                             out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return getContext().getFileStreamPath(name);
    }

You’d have to write a header to the archive? If yes, how?

https://stackoverflow.com/questions/22319372/to-convert-byte-array-to-mp3-file

2 answers

1


That solved my problem.

try {
                ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
                InputStream stream               = pssu.openStream();
                File mp3                         = new File(getFilesDir(), fileName.toLowerCase());
                OutputStream os                  = new FileOutputStream(mp3);

                byte[] buffer = new byte[4096];

                int len;
                while ((len = stream.read(buffer)) > 0) {
                    os.write(buffer, 0, len);
                }

                audios.add(mp3);

                byteBuffer.close();
                stream.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

1

To MP3 things work differently, files in this format suffer Ncode(encoding), this encoding allows raw data(bytes) suffer compression, this action will cause data loss, the whole process demands understanding of psychoacoustics, digital signal processing, discrete mathematics, etc, etc., all this is applied so that the losses during coding have the least possible human perception, therefore my dear, the header doesn’t even scratch the surface of complexity to create a file .mp3, the easiest way, in case you are not interested in knowing in depth how all this works will be to use some lib third party to carry out the encode.

A file WAV it is simple, there is no kind of encoding and loss of audio data.

  • 1

    I had a notion that an mp3 file was something complex, but not that complex. It left me interested in researching about. About the app: I’m considering changing the format to wav

Browser other questions tagged

You are not signed in. Login or sign up in order to post.