Strange issue in Combining Audio Files and playing in different API versions

旧城冷巷雨未停 提交于 2019-11-30 12:49:30
Yahia

Every audio file has its own header (includes information about length/samples etc.) - by combining the files the way you do the resulting file has multiple headers, one per source file (depending on the exact format with file offsets etc.). Thus the resulting file is NOT correct in terms of file format spec.

The newer Android version are more permissive and work/play with "multiple headers" present... the older versions do not...

To create a correctly combined audio file you must conform to the spec which among other things means creating one new header which describes all included audio...

Use for the the combination of audio files a different approach - for example via ffmpeg (see this for how to make ffmpeg for android).

Foreword: Haven't tested this, but I don't see why it shouldn't work.

Provided the headers ARE the cause of this problem, you can solve it really easily. Using the code you've given, the encoding is AMR-NB. According to this document the AMR header is simply the first 6 bytes, which are 0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A. If the headers in subsequent files are causing the issue, simply omit those bytes from subsequent files e.g.

write all bytes of first file
write from byte[6] -> byte[end] of subsequent files

Let me know how it goes.

EDIT: At request, change the try block to:

try{
        File f=new File(audNames.get(i));
        Log.v("Record Message", "File Length=========>>>"+f.length());
        fileContent = new byte[(int)f.length()];

        ///////////////new bit////////

        //same as you had, this opens a byte stream to the file
        ins=new FileInputStream(audNames.get(i));
        //reads fileContent.length bytes
        ins.read(fileContent);
        //now fileContent contains the entire audio file - in bytes.
        if(i>0){
            //we are not writing the first audio recording, but subsequent ones
            //so we don't want the header included in the write

            //copy the entire file, but not the first 6 bytes
            byte[] headerlessFileContent = new byte[fileContent.length()-6];
            for(int j=6; j<fileContent.length();j++){
                headerlessFileContent[j-6] = fileContent[j];
            }
            fileContent = headerlessFileContent;
        }
        ////////////////////////////

        Log.v("Record Message", "Number Of Bytes Readed=====>>>"+r);
        fos.write(fileContent);//Write the byte into the combine file.

        Log.v("Record Message", "File======="+i+"is Appended");

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