Concatenate mp3 files in Java

一曲冷凌霜 提交于 2020-02-06 07:50:14

问题


I have some problem with concatenation mp3 files. For example, I have 5 mp3 files. And I want concatenate them to one file.

I try this:

try {
    InputStream in = new FileInputStream("C:/a.mp3");
    byte[] buffer = new byte[1024];
    OutputStream os = new FileOutputStream(new File("C:/output.mp3",
            true));
    int count;
    while ((count = in.read(buffer)) != -1) {
        os.write(buffer, 0, count);
        os.flush();
    }
    in.close();
    in = new FileInputStream("C:/b.mp3");// second mp3
    while ((count = in.read(buffer)) != -1) {
        os.write(buffer, 0, count);
        os.flush();
    }
    in.close();
    os.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

But this do not working. I get one mp3 file on the finish of this process, it contains all music data from source mp3 files, but in Options I see time of fihish mp3 only from first source mp3 file. And, when I try use this final mp3 file when I use Xuggle library for adding this mp3 audio to mp4 video I get error.

I'm sure, problem in bytes from every mp3 source file, where recordered meta infromation. Maybe exist some library for correct concatenation mp3?


回答1:


There are multiple problems with you approach.

a.) If there are any meta data in the source files, you copy the meta data. In the concatinated file, those meta data (Id3v1 and Id3v2) will be present multiple times and worse, at locations where they are not supposed to be (Id3v1 must be located at the end of the file, Id3v2 at the beginning IIRC). This can confuse the decoder to recognize the file as corrupt (it may play the first section and then hiccup on the unexpected meta data of the 2nd part).

b.) Calculating the length of an MP3 isn't all that simple, one would need to count the number of MP3 frames in the file. Since there is no header that tells the number of frames, the only safe way to do this is scan the file sequentially (like a decode). This used to be a costly operation when MP3 was introduced, so there were multiple ways introduced to remedy this (VBR header block and Id3 meta tags). If your player relies on these, it will always detect the length as only the 1st part.

c.) Even if you strip away meta data properly, you can only concatenate MP3 streams using the same parameters (sample rate), some decoders may even have additional restrictions on bit rate and type (mono/MS/Istereo etc.).

You see, it can be done, but its not trivial.




回答2:


You cannot append this way music files. What you need is an external library (lame or...), in java is... almost imposible, JMF is dead.



来源:https://stackoverflow.com/questions/21381585/concatenate-mp3-files-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!