RandomAccessFile类初探:Java中解析wav音频文件信息:音频声道数,采样频率,采样位数、声音尺寸

最近在一个小伙伴问,jdk有没有处理音频文件,获取音频详细参数信息的API,因为之前也没有接触过音频,怀着学习的心态,一起在网上搜了一下,发现篇博客(https://www.iteye.com/blog/mzhj-1068237)有介绍。
暂时不清楚参数中的数字代表什么意思,先记录一下。
以下为摘抄的代码:

    public static int toInt(byte[] b) {    
        return (((b[3] & 0xff) << 24) + ((b[2] & 0xff) << 16) + ((b[1] & 0xff) << 8) + ((b[0] & 0xff) << 0));    
  }    
  
    public static short toShort(byte[] b) {
        return (short)((b[1] << 8) + (b[0] << 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 IOException {

        File f = new File("c:\\bong.wav");
        RandomAccessFile rdf = null;
        rdf = new RandomAccessFile(f,"r");
       
        System.out.println("audio size: " + toInt(read(rdf, 4, 4))); // 声音尺寸
       
        System.out.println("audio format: " + toShort(read(rdf, 20, 2))); // 音频格式 1 = PCM
       
        System.out.println("num channels: " + toShort(read(rdf, 22, 2))); // 1 单声道 2 双声道
       
        System.out.println("sample rate: " + toInt(read(rdf, 24, 4)));  // 采样率、音频采样级别 8000 = 8KHz
       
        System.out.println("byte rate: " + toInt(read(rdf, 28, 4)));  // 每秒波形的数据量
       
        System.out.println("block align: " + toShort(read(rdf, 32, 2)));  // 采样帧的大小
       
        System.out.println("bits per sample: " + toShort(read(rdf, 34, 2)));  // 采样位数
       
        rdf.close();
       
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容