M4A 是基於 MP4 容器格式的音訊檔案,其頭部資訊(如編碼格式、採樣率、聲道數、時長等)儲存在 MP4 的 box/atom 結構中。Java 標準庫無直接支援解析 MP4 容器,需借助第三方庫。
專案地址:https://github.com/sannies/mp4parser
此庫專為解析、建立、修改 MP4 容器設計,支援 M4A、MP4、3GP 等格式,純 Java 實現,無原生相依性。
<dependency>
<groupId>com.googlecode.mp4parser</groupId>
<artifactId>isoparser</artifactId>
<version>1.1.22</version> <!-- 請檢查最新版本 -->
</dependency>
import com.googlecode.mp4parser.IsoFile;
import com.googlecode.mp4parser.boxes.mp4.sampleentry.AudioSampleEntry;
import com.googlecode.mp4parser.boxes.iso14496.part12.TrackBox;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
public class M4AInfoReader {
public static void main(String[] args) throws Exception {
File file = new File("test.m4a");
try (FileChannel fc = new RandomAccessFile(file, "r").getChannel()) {
IsoFile isoFile = new IsoFile(fc);
// 遍歷所有 Track
for (TrackBox track : isoFile.getMovieBox().getBoxes(TrackBox.class)) {
AudioSampleEntry ase = track.getMediaBox()
.getMediaInformationBox()
.getSampleTableBox()
.getSampleDescriptionBox()
.getBoxes(AudioSampleEntry.class).get(0);
System.out.println("編碼格式: " + ase.getType()); // mp4a
System.out.println("採樣率: " + ase.getSampleRate());
System.out.println("聲道數: " + ase.getChannelCount());
System.out.println("位元深度: " + ase.getSampleSize());
}
// 時長計算(以 movie timescale 為單位)
long duration = isoFile.getMovieBox().getMovieHeaderBox().getDuration();
long timescale = isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
System.out.println("時長(秒): " + (duration / (double)timescale));
}
}
}
使用 mp4parser 是純 Java 環境下讀取 M4A 頭部資訊最輕量、標準的方案,程式碼簡潔且無外部相依。