public static void parseWavHeader(byte[] audioStream) throws IOException {
? ? ? ? ByteArrayInputStream inputStream = new ByteArrayInputStream(audioStream);
? ? ? ? // 驗(yàn)證RIFF標(biāo)識
? ? ? ? byte[] riff = new byte[4];
? ? ? ? inputStream.read(riff);
? ? ? ? String riffIdentifier = new String(riff);
? ? ? ? if (!"RIFF".equals(riffIdentifier)) {
? ? ? ? ? ? throw new IOException("Not a valid WAV file.");
? ? ? ? }
? ? ? ? // 文件大小
? ? ? ? int fileSize = readInt(inputStream);
? ? ? ? // WAVE標(biāo)識
? ? ? ? byte[] wave = new byte[4];
? ? ? ? inputStream.read(wave);
? ? ? ? // fmt塊
? ? ? ? byte[] fmt = new byte[4];
? ? ? ? inputStream.read(fmt);
? ? ? ? // fmt塊大小
? ? ? ? int fmtSize = readInt(inputStream);
? ? ? ? // 音頻格式
? ? ? ? int audioFormat = readShort(inputStream);
? ? ? ? // 通道數(shù)
? ? ? ? int numChannels = readShort(inputStream);
? ? ? ? // 采樣率
? ? ? ? int sampleRate = readInt(inputStream);
? ? ? ? // 字節(jié)率
? ? ? ? int byteRate = readInt(inputStream);
? ? ? ? // 塊對齊
? ? ? ? int blockAlign = readShort(inputStream);
? ? ? ? // 每樣本位數(shù)
? ? ? ? int bitsPerSample = readShort(inputStream);
? ? ? ? // data塊
? ? ? ? byte[] dataIdentifier = new byte[4];
? ? ? ? inputStream.read(dataIdentifier);
? ? ? ? if (!"data".equals(new String(dataIdentifier))) {
? ? ? ? ? ? throw new IOException("Missing data chunk.");
? ? ? ? }
? ? ? ? // 數(shù)據(jù)大小
? ? ? ? int dataSize = readInt(inputStream);
? ? ? ? // 打印解析結(jié)果
? ? ? ? System.out.println("RIFF Identifier: " + riffIdentifier);
? ? ? ? System.out.println("File Size: " + fileSize);
? ? ? ? System.out.println("WAVE Identifier: " + new String(wave));
? ? ? ? System.out.println("Format: " + new String(fmt));
? ? ? ? System.out.println("Format Size: " + fmtSize);
? ? ? ? System.out.println("Audio Format: " + audioFormat);
? ? ? ? System.out.println("Number of Channels: " + numChannels);
? ? ? ? System.out.println("Sample Rate: " + sampleRate);
? ? ? ? System.out.println("Byte Rate: " + byteRate);
? ? ? ? System.out.println("Block Align: " + blockAlign);
? ? ? ? System.out.println("Bits per Sample: " + bitsPerSample);
? ? ? ? System.out.println("Data Identifier: " + new String(dataIdentifier));
? ? ? ? System.out.println("Data Size: " + dataSize);
? ? ? ? // 提取實(shí)際音頻數(shù)據(jù)(可選)
? ? ? ? byte[] audioData = new byte[dataSize];
? ? ? ? inputStream.read(audioData); // 提取音頻數(shù)據(jù)
? ? }
? ? private static int readInt(ByteArrayInputStream stream) throws IOException {
? ? ? ? byte[] buffer = new byte[4];
? ? ? ? stream.read(buffer);
? ? ? ? return ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt();
? ? }
? ? private static short readShort(ByteArrayInputStream stream) throws IOException {
? ? ? ? byte[] buffer = new byte[2];
? ? ? ? stream.read(buffer);
? ? ? ? return ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getShort();
? ? }
}