日期:2014-05-20  浏览次数:21136 次

想写一个将双声道的 wav 转成 单声道的 wav,生成的却是噪音,不知哪里错了。

package test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Test1
{
    public static void main(String[] args) throws Exception
    {
        File file = new File("T:\\temp\\tada.wav").getAbsoluteFile();
        System.out.println(file.getName());
        BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
        RIFFHeader riff = new RIFFHeader(input);
        System.out.println(riff.getID());
        System.out.println(riff.getSize());
        System.out.println(riff.getFormat());
        WAVEHeader wave = new WAVEHeader(input);
        System.out.println(wave.getID());
        System.out.println(wave.getSize());
        System.out.println(wave.getFormatTag());
        System.out.println(wave.getChannels());
        System.out.println(wave.getSamplesPerSec());
        System.out.println(wave.getAvgBytesPerSec());
        System.out.println(wave.getBlockAlign());
        System.out.println(wave.getBitsPerSample());
        System.out.println(wave.getOther());
        DataHeader data = new DataHeader(input);
        System.out.println(data.getID());
        System.out.println(data.getSize());
        BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(new File(file.getParentFile(), file.getName() + ".out")));
        writeString(output, riff.getID());
        writeInteger(output, 4, data.getSize() / wave.getChannels() + 8 + wave.getSize() + 8 + 4);
        writeString(output, riff.getFormat());
        writeString(output, wave.getID());
        writeInteger(output, 4, wave.getSize());
        writeInteger(output, 2, wave.getFormatTag());
        writeInteger(output, 2, 1);
        writeInteger(output, 4, wave.getSamplesPerSec());
        writeInteger(output, 4, wave.getAvgBytesPerSec() / wave.getChannels());
        writeInteger(output, 2, wave.getBlockAlign() / wave.getChannels());
        writeInteger(output, 2, wave.getBitsPerSample());
        if (wave.getSize() != 16)
        {
            writeString(output, wave.getOther());
        }
        writeString(output, data.getID());
        writeInteger(output, 4, data.getSize() / wave.getChannels());
        int byteCount = wave.getBitsPerSample() / 8;
        int frameCount = data.getSize() / wave.getChannels() / byteCount;
        int[] frames = new int[wave.getChannels()];
        int frame;
        for (int i = 0; i < frameCount; i++)
        {
            for (int f = 0; f < frames.length; f++)
            {
                frame = 0;
                for (int d = 0; d < byteCount; d++)
                {
                    frame += input.read() << (d * 8);