Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 合併多個 AMR 音檔

需求很明確:把兩個 amr 格式的音訊檔合成一個。關鍵知識是 amr 的檔頭固定為 6 個位元組,因此除了第一個檔案要整份寫入,後續檔案都要先跳過檔頭再附加,否則播放器會在中途遇到第二個檔頭而停止。

/**
 * 需求:將兩個 amr 格式音訊檔合併為 1 個
 * 注意:amr 格式的檔頭為 6 個位元組的長度
 * @param partsPaths     各部分路徑
 * @param unitedFilePath 合併後路徑
 */
public void uniteAMRFile(String[] partsPaths, String unitedFilePath) {
    try {
        File unitedFile = new File(unitedFilePath);
        FileOutputStream fos = new FileOutputStream(unitedFile);
        RandomAccessFile ra = null;
        for (int i = 0; i < partsPaths.length; i++) {
            ra = new RandomAccessFile(partsPaths[i], "r");
            if (i != 0) {
                ra.seek(6);
            }
            byte[] buffer = new byte[1024 * 8];
            int len = 0;
            while ((len = ra.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        }
        ra.close();
        fos.close();
    } catch (Exception e) {
    }
}

幾個可以再加強的地方:catch 區塊空白會把錯誤全部吞掉,除錯時會非常痛苦,至少該印出堆疊;ra 與 fos 建議用 try-with-resources 管理,避免例外時檔案控制代碼外洩;另外這個做法只適用於編碼參數完全一致的同格式音檔,若取樣率或模式不同,合併後會出現雜訊,那種情況就得先解碼成 PCM 再重新編碼。

Copyright © Linux教程網 All Rights Reserved