How to recognize the audio stream format?

2019-09-06 13:03发布

问题:

Here I have the code which records a audio stream to file. The problem is I'd like to save this file with correct file extension (mainly .mp3 and .aac). How can I achieve this?

URLConnection conn = new URL(StringUrls[0]).openConnection();
            InputStream in = conn.getInputStream();

            BufferedOutputStream bufOutstream = new BufferedOutputStream(new FileOutputStream(new File(env.getExternalStorageDirectory()+"/temp.file")));

            byte[] buffer = new byte[4096];
            int len = in.read(buffer);
            while (len != -1) {
                bufOutstream.write(buffer, 0, len);
                len = in.read(buffer);

                if (Recorder.this.isCancelled) break;

            }
            bufOutstream.close();

回答1:

One way would be to take a look at the binary data while you already have it in your hands. According to this File signatures table both MP3 and AAC have unique magic headers:

  • 49 44 33 for MPEG-1 Audio Layer 3 (MP3) audio file
  • FF F1 for MPEG-4 Advanced Audio Coding (AAC) Low Complexity (LC) audio
  • FF F9 for MPEG-2 Advanced Audio Coding (AAC) Low Complexity (LC) audio