Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實現 MP3 剪切與合併:從幀解析到文件拼接

編輯:關於 Android 程式設計

早前做過一個音樂播放器,在線播放、下載、歌詞顯示、分享這些常規功能都有,其中「铃声剪輯」這塊是最有意思的。這篇文章把剪切與合併的實現思路和關鍵代碼整理出來——先看原理,代碼才看得明白。

為什麼不能直接按字節切

很多人第一反應是「按時間比例算字節位置,切一刀不就完了」。這樣做的結果是切出來的片段往往無法正常播放,或者開頭有杂音。原因在於 MP3 文件的結構:文件頭部可能有 ID3v2 標籤,尾部可能有 ID3v1 標籤(固定 128 字節,以 TAG 三個字符開頭)。這些都是元數據,不是音頻數據。

所以第一步必須先把標籤剝離,得到純粹的音頻數據幀序列。

第一步:剝離 ID3 標籤

ID3v2 在文件頭部,格式是前 3 字節為 ID3,第 6~9 字節記錄了標籤大小(每個字節只有低 7 位有效,需要按大端方式組合,最後再加上 10 字節的頭部)。ID3v1 在尾部固定 128 字節。

public static String fenLiData(String path) throws IOException {
    File file  = new File(path);
    File file1 = new File(path + "01");    // 剝離 ID3v2 後的中間文件
    File file2 = new File(path + "001");   // 剝離 ID3v1 後的最終文件

    RandomAccessFile rf = new RandomAccessFile(file, "rw");
    FileOutputStream fos = new FileOutputStream(file1);

    byte[] ID3 = new byte[3];
    rf.read(ID3);

    if (new String(ID3).equals("ID3")) {
        rf.seek(6);
        byte[] ID3size = new byte[4];
        rf.read(ID3size);
        int size = ((ID3size[0] & 0x7f) << 21) + ((ID3size[1] & 0x7f) << 14)
                 + ((ID3size[2] & 0x7f) << 7)  +  (ID3size[3] & 0x7f) + 10;
        rf.seek(size);                    // 跳過整個 ID3v2 塊
    } else {
        rf.seek(0);                       // 沒有 ID3v2,從頭拷貝
    }
    int lens;
    byte[] bs = new byte[1024 * 4];
    while ((lens = rf.read(bs)) != -1) fos.write(bs, 0, lens);
    fos.close();
    rf.close();

    // 再處理尾部的 ID3v1
    RandomAccessFile raf = new RandomAccessFile(file1, "rw");
    byte[] TAG = new byte[3];
    raf.seek(raf.length() - 128);
    raf.read(TAG);

    FileOutputStream fs = new FileOutputStream(file2);
    if (new String(TAG).equals("TAG")) {
        byte[] data = new byte[(int) (raf.length() - 128)];
        raf.seek(0);
        raf.read(data);
        fs.write(data);
    } else {
        raf.seek(0);
        byte[] data = new byte[1024 * 4];
        int len;
        while ((len = raf.read(data)) != -1) fs.write(data, 0, len);
    }
    raf.close();
    fs.close();
    if (file1.exists()) file1.delete();   // 清理中間文件
    return file2.getAbsolutePath();
}

第二步:解析每一幀的長度

MP3 由一個個「幀」組成,每幀有 4 字節的幀頭,其中包含比特率、採樣率、填充位等信息。幀長的計算公式(MPEG1 Layer3)是:

幀長 = 144 × 比特率 / 採樣率 + 填充位

比特率和採樣率都通過查表得到:

private static int getBitRate(int i) {
    int[] a = {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0};
    return a[i];
}
private static int getSampleRate(int i) {
    int[] a = {44100, 48000, 32000, 0};
    return a[i];
}

public static List<Integer> initMP3Frame(String path) {
    File file = new File(path);
    List<Integer> list = new ArrayList<>();
    int frameSize = 0;
    try (RandomAccessFile rad = new RandomAccessFile(file, "rw")) {
        byte[] head = new byte[4];
        while (frameSize < rad.length()) {
            rad.seek(frameSize);
            rad.read(head);
            int bitRate   = getBitRate((head[2] >> 4) & 0x0f) * 1000;
            int sampleRate = getSampleRate((head[2] >> 2) & 0x03);
            int padding   = (head[2] >> 1) & 0x01;
            if (bitRate == 0 || sampleRate == 0) return null;   // 解析失敗
            int len = 144 * bitRate / sampleRate + padding;
            list.add(len);        // 記錄每幀長度
            frameSize += len;
        }
    } catch (IOException e) {
        return null;
    }
    return list;
}

把每幀長度存進 List 之後,任意時間點就能換算成「第幾幀」,進而換算成字節偏移。這裡用了一個近似:幀序號 = 時間(秒) / 0.026,因爲 44.1kHz 單幀時長約為 26ms。

第三步:按幀範圍剪切

public static String CutingMp3(String path, String name, List<Integer> list,
                               double startTime, double stopTime) throws IOException {
    int start = (int) (startTime / 0.026);
    int stop  = (int) (stopTime  / 0.026);

    // 邊界校驗,防止越界
    if (start > stop || start < 0 || stop < 0 || stop > list.size()) return null;

    long seekStart = 0;
    for (int i = 0; i < start; i++) seekStart += list.get(i);
    long seekStop = seekStart;
    for (int i = start; i < stop; i++) seekStop += list.get(i);

    String dir = "/storage/emulated/0/HH音樂播放器/切割/";
    new File(dir).mkdirs();
    File out = new File(dir + name + "(HH切割).mp3");

    try (RandomAccessFile raf = new RandomAccessFile(path, "rw");
         FileOutputStream fos = new FileOutputStream(out)) {
        raf.seek(seekStart);
        byte[] bs = new byte[(int) (seekStop - seekStart)];
        raf.read(bs);
        fos.write(bs);
    }
    return out.getAbsolutePath();
}

注意輸入的 path 應該是上一步剝離標籤後的文件路徑,這樣切出來的新文件本身不含 ID3 標籤,播放器會按默認信息處理。

合併:追加寫入即可

合併比剪切簡單得多。先分別對兩個文件做標籤剝離,然後依次把兩個純數據流寫進同一個目標文件——第二次打開輸出流時用追加模式(new FileOutputStream(file2, true))。

public static String heBingMp3(String path, String path1, String name) throws IOException {
    String data1 = fenLiData(path);
    String data2 = fenLiData(path1);

    String dir = "/storage/emulated/0/HH音樂播放器/合並/";
    new File(dir).mkdirs();
    File target = new File(dir + name + "(HH合並).mp3");

    copyStream(new FileInputStream(data1), new FileOutputStream(target));
    copyStream(new FileInputStream(data2), new FileOutputStream(target, true));  // 追加

    new File(data1).delete();
    new File(data2).delete();
    return target.getAbsolutePath();
}

private static void copyStream(InputStream in, OutputStream out) throws IOException {
    try (InputStream i = in; OutputStream o = out) {
        byte[] bs = new byte[1024 * 4];
        int len;
        while ((len = i.read(bs)) != -1) o.write(bs, 0, len);
    }
}

使用順序與注意事項

調用順序是固定的:fenLiData → initMP3Frame → CutingMp3 / heBingMp3。因爲涉及 SD 卡讀寫,記得申請存儲權限;因爲是耗時操作,必須放在子線程中執行,完成後切回主線程更新 UI。

String data = CaoZuoMp3Utils.fenLiData(str);
List<Integer> list = CaoZuoMp3Utils.initMP3Frame(data);
if (list == null) {
    // 解析失敗,提示用戶
} else {
    String result = CaoZuoMp3Utils.CutingMp3(data, cuting_name, list, start, stop);
}

實戰中還有幾點值得留意:中間文件(path + "01" 這種)如果在工具類內部刪不掉,就在調用方完成後補一次刪除,避免垃圾文件佔用空間;合併後的文件沒有重新寫 ID3 標籤,音頻信息會丟失,若在意可以自行補寫;另外本文的算法基於 MPEG1 Layer3,遇到 VBR(可變比特率)文件時幀長計算會不準,需要額外解析 Xing/Info 頭。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved