简体   繁体   English

如何在android中合并两个或多个mp3音频文件?

[英]How to merge two or more mp3 audio file in android?

I'm trying to merge mp3 audio files But not successful.我正在尝试合并 mp3 音频文件但没有成功。

Here is my code.这是我的代码。

public static void meargeAudio(List<File> filesToMearge)
{


    while (filesToMearge.size()!=1){

        try {
            FileInputStream fistream1 = new FileInputStream(new File(filesToMearge.get(0).getPath()));  //(/storage/emulated/0/Audio Notes/1455194356500.mp3) first source file
            FileInputStream fistream2 = new FileInputStream(new File(filesToMearge.get(1).getPath()));//second source file

            File file1 = new File(filesToMearge.get(0).getPath());
            boolean deleted = file1.delete();
            File file2 = new File(filesToMearge.get(1).getPath());
            boolean deleted1 = file2.delete();

            SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
            FileOutputStream fostream = new FileOutputStream(new File(filesToMearge.get(0).getPath()),true);//destinationfile

            int temp;

            while ((temp = sistream.read()) != -1) {
                // System.out.print( (char) temp ); // to print at DOS prompt
                fostream.write(temp);   // to write to file
            }

            filesToMearge.add(0,new File(filesToMearge.get(0).getPath()));
            filesToMearge.remove(1);
            filesToMearge.remove(1);


            fostream.close();
            sistream.close();
            fistream1.close();
            fistream2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

eg例如

firstFileSize =12kb第一个文件大小 =12kb

secondFileSize =10kb第二个文件大小 =10kb

finalfileSize=22kb最终文件大小=22kb

Size is accurate But sound is missing尺寸准确但缺少声音

No error but in result i found finalfile contains only first file audio second file audio is missing.没有错误,但结果我发现 finalfile 只包含第一个文件音频第二个文件音频丢失。

Don't know what is the issue.if any one know the solution help me.不知道是什么问题。如果有人知道解决方案,请帮助我。

Thanks谢谢

I also struggled with that and solved it using mp4parser我也为此苦苦挣扎并使用mp4parser解决了它

import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.AppendTrack;

For your case, I believe something like this should work:对于你的情况,我相信这样的事情应该有效:

public static void mergeAudio(List<File> filesToMerge) {

    String output = Environment.getExternalStorageDirectory().getAbsolutePath() + "output.mp3";

    while (filesToMerge.size()!=1){

        try {

            String[] videoUris = new String[]{
                filesToMerge.get(0).getPath(),
                filesToMerge.get(0).getPath()
            };

            List<Track> videoTracks = new LinkedList<Track>();
            List<Track> audioTracks = new LinkedList<Track>();

            for (Movie m : inMovies) {
                for (Track t : m.getTracks()) {
                    if (t.getHandler().equals("soun")) {
                        audioTracks.add(t);
                    }
                    if (t.getHandler().equals("vide")) {
                        videoTracks.add(t);
                    }
                }
            }

            Movie result = new Movie();

            if (!audioTracks.isEmpty()) {
                result.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
            }
            if (!videoTracks.isEmpty()) {
                result.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()])));
            }

            Container out = new DefaultMp4Builder().build(result);

            FileChannel fc = new RandomAccessFile(output, "rw").getChannel();
            out.writeContainer(fc);
            fc.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

There are a few answers suggesting that, such as:有几个答案表明,例如:

It is too late.太晚了。 But still, someone might need a proper solution.但是,仍然有人可能需要一个适当的解决方案。 That is why I am suggesting using AudioMixer-android library.这就是为什么我建议使用AudioMixer-android库。

Well there's a function to merge Audio or Video files那么有一个功能来合并音频或视频文件

public static boolean mergeMediaFiles(boolean isAudio, String sourceFiles[], String targetFile) {
        try {
            String mediaKey = isAudio ? "soun" : "vide";
            List<Movie> listMovies = new ArrayList<>();
            for (String filename : sourceFiles) {
                listMovies.add(MovieCreator.build(filename));
            }
            List<Track> listTracks = new LinkedList<>();
            for (Movie movie : listMovies) {
                for (Track track : movie.getTracks()) {
                    if (track.getHandler().equals(mediaKey)) {
                        listTracks.add(track);
                    }
                }
            }
            Movie outputMovie = new Movie();
            if (!listTracks.isEmpty()) {
                outputMovie.addTrack(new AppendTrack(listTracks.toArray(new Track[listTracks.size()])));
            }
            Container container = new DefaultMp4Builder().build(outputMovie);
            FileChannel fileChannel = new RandomAccessFile(String.format(targetFile), "rws").getChannel();
            container.writeContainer(fileChannel);
            fileChannel.close();
            return true;
        }
        catch (IOException e) {
            Log.e("MYTAG", "Error merging media files. exception: "+e.getMessage());
            return false;
        }
    }
  • If you got Audios, isAudio should be true.如果你有音频, isAudio应该是真的。 if you got videos isAudio should be false如果你有视频isAudio应该是假的
  • sourceFiles[] array should contain the destinations of the media files such as sourceFiles[]数组应包含媒体文件的目的地,例如

    /sdcard/my_songs/audio_1, /sdcard/my_songs/audio_2, /sdcard/my_songs/audio_3

  • targetFile is your final audio merged file should be somthing like targetFile是你最终的音频合并文件应该是这样的

    /sdcard/my_songs/final_audio_1

  • If you deal with large files it's preferred to merge file in background, you can use AsynkTask如果您处理大文件,最好在后台合并文件,您可以使用AsynkTask

String wavFile1 = android.os.Environment.getExternalStorageDirectory()+"/Download/a.mp4"; String wavFile1 = android.os.Environment.getExternalStorageDirectory()+"/Download/a.mp4"; String wavFile2 = android.os.Environment.getExternalStorageDirectory()+"/Download/b.mp4"; String wavFile2 = android.os.Environment.getExternalStorageDirectory()+"/Download/b.mp4"; FileInputStream fistream1 = null; FileInputStream fistream1 = null; // first source file try { fistream1 = new FileInputStream(wavFile1); // 第一个源文件 try { fistream1 = new FileInputStream(wavFile1); FileInputStream fistream2 = new FileInputStream(wavFile2);//second source file SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2); FileInputStream fistream2 = new FileInputStream(wavFile2);//第二个源文件SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2); FileOutputStream fostream = new FileOutputStream(android.os.Environment.getExternalStorageDirectory()+"/Download/merge1.mp4");//destinationfile FileOutputStream fostream = new FileOutputStream(android.os.Environment.getExternalStorageDirectory()+"/Download/merge1.mp4");//目标文件

        int temp;

        while( ( temp = sistream.read() ) != -1)
        {
            // System.out.print( (char) temp ); // to print at DOS prompt
            fostream.write(temp);   // to write to file
        }
        Log.e("Result","Done");

        fostream.close();
        sistream.close();
        fistream1.close();
        fistream2.close();

        Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.e("Not",e+"");
        Toast.makeText(this, "File not Found", Toast.LENGTH_SHORT).show();
    }
    catch (IOException e)
    {
        Toast.makeText(this, ""+e, Toast.LENGTH_SHORT).show();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM