import java.io.*;
import java.util.*;
public class CWav_1 {
public static int toInt(byte[] bs) {
return ((bs[3] << 24) + (bs[2] << 16) + (bs[1] << 8) + (bs[0] << 0));
}
public static short toShort(byte[] bs) {
return (short)((bs[1] << 8) + (bs[0] << 0));
}
public static byte[] readBytes(RandomAccessFile rd, int pos, int length) throws IOException {
rd.seek(pos);
byte result[] = new byte[length];
for (int i = 0; i < length; i++) {
result[i] = rd.readByte();
}
return result;
}
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
RandomAccessFile rd = new RandomAccessFile(file,"r");
System.out.println("wav size: " + toInt(readBytes(rd, 4, 4)));
System.out.println("wav format: " + toShort(readBytes(rd, 20, 2)));
System.out.println("channels count: " + toShort(readBytes(rd, 22, 2)));
System.out.println("sample rate: " + toInt(readBytes(rd, 24, 4)));
System.out.println("byte rate: " + toInt(readBytes(rd, 28, 4)));
System.out.println("block align: " + toShort(readBytes(rd, 32, 2)));
System.out.println("bits per sample: " + toShort(readBytes(rd, 34, 2)));
rd.close();
}
}
当读到文件内部是 0x803f 时结果出错了
后来改为:
import java.io.*;
import java.util.*;
public class CWav_2 {
public static int toInt(byte[] bs) {
int ds[] = new int[4];
for (int i = 0; i < 4; i++) {
ds[i] = ((bs[i]) >= 0 ? bs[i] : 256 + bs[i]);
}
return ((ds[3] << 24) | (ds[2] << 16) | (ds[1] << 8) | (ds[0] << 0));
}
public static short toShort(byte[] bs) {
return (short)((bs[1] << 8) | (bs[0] << 0));
}
public static byte[] readBytes(RandomAccessFile rd, int pos, int length) throws IOException {
rd.seek(pos);
byte result[] = new byte[length];
for (int i = 0; i < length; i++) {
result[i] = rd.readByte();
}
return result;
}
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
RandomAccessFile rd = new RandomAccessFile(file,"r");
System.out.println("wav size: " + toInt(readBytes(rd, 4, 4)));
System.out.println("wav format: " + toShort(readBytes(rd, 20, 2)));
System.out.println("channels count: " + toShort(readBytes(rd, 22, 2)));
System.out.println("sample rate: " + toInt(readBytes(rd, 24, 4)));
System.out.println("byte rate: " + toInt(readBytes(rd, 28, 4)));
System.out.println("block align: " + toShort(readBytes(rd, 32, 2)));
System.out.println("bits per sample: " + toShort(readBytes(rd, 34, 2)));
rd.close();
}
}
Java 中没有无符号数,在读字节数组转换的时候需要注意溢出的情况 , 后来这样做结果才正确。。。。
唉~要是java有unsigned 类型结果就没这么麻烦了.....