Подтвердить что ты не робот

Соедините два аудиофайла и воспроизведите полученный файл

Я действительно сталкиваюсь с проблемой за последние пару дней, но я не могу найти точное решение, пожалуйста, помогите мне.

Я хочу объединить два .mp3 или любой аудиофайл и воспроизвести финальный один один mp3 файл. Но когда я совмещаю два файла, окончательный размер файла в порядке, но когда я пытаюсь воспроизвести его, просто играйте в первый файл, я пробовал это с помощью SequenceInputStream или байтового массива, но я не могу получить точный результат, пожалуйста, помогите мне.

Мой код следующий:

public class MerginFileHere extends Activity {
public ArrayList<String> audNames;
byte fileContent[];
byte fileContent1[];
FileInputStream ins,ins1;
FileOutputStream fos = null;
String combined_file_stored_path = Environment
        .getExternalStorageDirectory().getPath()
        + "/AudioRecorder/final.mp3";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    audNames = new ArrayList<String>();
    String file1 = Environment.getExternalStorageDirectory().getPath()
            + "/AudioRecorder/one.mp3";

    String file2 = Environment.getExternalStorageDirectory().getPath()
            + "/AudioRecorder/two.mp3";

    File file = new File(Environment.getExternalStorageDirectory()
            .getPath() + "/AudioRecorder/" + "final.mp3");

    try {
        file.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    audNames.add(file1);
    audNames.add(file2);

    Button btn = (Button) findViewById(R.id.clickme);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            createCombineRecFile();
        }
    });
}

public void createCombineRecFile() {
    // String combined_file_stored_path = // File path in String to store
    // recorded audio

    try {
        fos = new FileOutputStream(combined_file_stored_path, true);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

        try {
            File f = new File(audNames.get(0));
            File f1 = new File(audNames.get(1));
            Log.i("Record Message", "File Length=========>>>" + f.length()+"------------->"+f1.length());


            fileContent = new byte[(int) f.length()];
            ins = new FileInputStream(audNames.get(0));
            int r = ins.read(fileContent);// Reads the file content as byte

            fileContent1 = new byte[(int) f1.length()];
            ins1 = new FileInputStream(audNames.get(1));
            int r1 = ins1.read(fileContent1);// Reads the file content as byte
                                            // from the list.






            Log.i("Record Message", "Number Of Bytes Readed=====>>>" + r);

            //fos.write(fileContent1);// Write the byte into the combine file.


            byte[] combined = new byte[fileContent.length + fileContent1.length];

            for (int i = 0; i < combined.length; ++i)
            {
                combined[i] = i < fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length];
            }
            fos.write(combined);
            //fos.write(fileContent1);*



        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    try {
        fos.close();
        Log.v("Record Message", "===== Combine File Closed =====");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}
4b9b3361

Ответ 1

Я уже опубликовал приложение с этой функцией... попробуйте мой метод с помощью SequenceInputStream, в моем приложении я просто объединил 17 файлов MP3 в одном и воспроизвел его с помощью библиотеки JNI MPG123, но я протестировал файл с помощью MediaPlayer без проблем.

Этот код не самый лучший, но он работает...

private void mergeSongs(File mergedFile,File...mp3Files){
        FileInputStream fisToFinal = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mergedFile);
            fisToFinal = new FileInputStream(mergedFile);
            for(File mp3File:mp3Files){
                if(!mp3File.exists())
                    continue;
                FileInputStream fisSong = new FileInputStream(mp3File);
                SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
                byte[] buf = new byte[1024];
                try {
                    for (int readNum; (readNum = fisSong.read(buf)) != -1;)
                        fos.write(buf, 0, readNum);
                } finally {
                    if(fisSong!=null){
                        fisSong.close();
                    }
                    if(sis!=null){
                        sis.close();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(fos!=null){
                    fos.flush();
                    fos.close();
                }
                if(fisToFinal!=null){
                    fisToFinal.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } 

Ответ 2

Mp3 файлы - это некоторые фреймы.

Вы можете объединить эти файлы, добавив потоки друг другу , если и только если bit rate и sample rate ваших файлов одинаковы.

Если нет, первый файл воспроизводится, потому что у него действительно истинная кодировка, но второй файл не может декодироваться в настоящий mp3 файл.

Предложение: конвертируйте файлы с определенными bit rate и sample rate, затем используйте свою функцию.