Java輕松使用工具類實現獲取wav時間長度

獲取wav格式音頻時長。

Maven依賴

        <dependency>
            <groupId>org</groupId>
            <artifactId>jaudiotagger</artifactId>
            <version>2.0.1</version>
        </dependency>

工具類

import org.jaudiotagger.audio.wav.util.WavInfoReader;
 
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
 
/** @Author huyi @Date 2021/9/30 14:46 @Description: 音頻工具類 */
public class AudioWavUtils {
 
  public static void getWavInfo(String filePath) throws Exception {
    File file = new File(filePath);
    WavInfoReader wavInfoReader = new WavInfoReader();
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    // wav音頻時長
    long duration = (long) (wavInfoReader.read(raf).getPreciseLength() * 1000);
    // wav音頻采樣率
    int sampleRate = toInt(read(raf, 24, 4));
    System.out.println("duration -> " + duration + ",sampleRate -> " + sampleRate);
    raf.close();
  }
 
  public static int toInt(byte[] b) {
    return ((b[3] << 24) + (b[2] << 16) + (b[1] << 8) + (b[0]));
  }
 
  public static byte[] read(RandomAccessFile rdf, int pos, int length) throws IOException {
    rdf.seek(pos);
    byte[] result = new byte[length];
    for (int i = 0; i < length; i++) {
      result[i] = rdf.readByte();
    }
    return result;
  }
 
  public static void main(String[] args) throws Exception {
    getWavInfo("E:\\csdn\\dzgz.wav");
  }
}

輸出結果:

duration為音頻時長,單位毫秒,sampleRate為采樣率。

說明

該工具類隻能處理單聲道音頻,雙聲道會報錯,多聲道屬於立體聲范疇,提醒一下。

到此這篇關於Java輕松使用工具類實現獲取wav時間長度的文章就介紹到這瞭,更多相關Java 獲取wav時長內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: