Java獲取音頻播放時長

1. 獲取.amr音頻文件播放時長java

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
 
public class AmrFileTimeLengthSample {
	public static long getAmrDuration(File file) throws IOException {
        long duration = -1;
        int[] packedSize = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 };
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "rw");
            long length = file.length();//文件的長度
            int pos = 6;//設置初始位置
            int frameCount = 0;//初始幀數
            int packedPos = -1;
            byte[] datas = new byte[1];//初始數據值
            while (pos <= length) {
                randomAccessFile.seek(pos);
                if (randomAccessFile.read(datas, 0, 1) != 1) {
                    duration = length > 0 ? ((length - 6) / 650) : 0;
                    break;
                }
                packedPos = (datas[0] >> 3) & 0x0F;
                pos += packedSize[packedPos] + 1;
                frameCount++;
            }
            duration += frameCount * 20;//幀數*20
        } finally {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        }
        return duration;
    }
}

2. 獲取.mp3,.wav,.wma音頻文件播放時長dom

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import java.io.File;

.................................

    File source = new File(fileUrl);
    Encoder encoder = new Encoder();
    MultimediaInfo m = encoder.getInfo(source);
    long duration = m.getDuration();
相關文章
相關標籤/搜索