java—将16位PCM转换为.wav,在切换endianness后,.wav文件向后播放

iszxjhcz  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(380)

我试图建立一个android应用程序,记录pcm音频,并将其导出为wav文件。
它对8bitpcm工作得很好,但是当我切换到16bitpcm时,我得到了白噪声。
我终于发现这是字节数组的尾数,但是现在,在从小尾数转换为大尾数之后,我的音频非常清晰,但是相反!
下面是我如何调用该方法: byte[] inputByteArray = convertLittleEndianToBig(readToByte(input)); 然后字节[]被附加到我的.wav头中:

OutputStream os;
        os = new FileOutputStream(output);
        BufferedOutputStream bos = new BufferedOutputStream(os);
        DataOutputStream outFile = new DataOutputStream(bos);

        // Adding header here...

        outFile.write(inputByteArray);

convertlittleendiantobig():

public static byte[] convertLittleEndianToBig(byte[] value) {
    final int length = value.length;
    byte[] res = new byte[length];
    for(int i = 0; i < length; i++) {
        res[length - i - 1] = value[i];
    }
    return res;
}

还有。。。。readtobyte():

public static byte[] readToByte(File file) throws IOException, FileNotFoundException {
    if (file.length() < MAX_FILE_SIZE && file.length() != 0L) {
        ByteArrayOutputStream ous = null;
        InputStream ios = null;
        try {
            byte[] buffer = new byte[4096];
            ous = new ByteArrayOutputStream();
            ios = new FileInputStream(file);
            int read = 0;
            while ((read = ios.read(buffer)) != -1) {
                ous.write(buffer, 0, read);
            }
        } finally {
            try {
                if (ous != null)
                    ous.close();
            } catch (IOException e) {
            }

            try {
                if (ios != null)
                    ios.close();
            } catch (IOException e) {
            }
        }
        return ous.toByteArray();
    }
    else {
    return new byte[0];
    }

太奇怪了,音频听起来完全正确,但是向后。
如果我取消对“convertlittleendiantobig()”的调用,我将返回到白噪声静态。
谢谢你的帮助。这是我第一个真正的项目。

xkrw2x1b

xkrw2x1b1#

我是个白痴-16比特!=一个字节。
我正在反转字节数组,而我本应该反转一个短数组。
最后我用以下取代了littleendiantobig:

public static short[] convertLittleBytesToBigShorts(byte[] value) {

    short[] shorts = new short[value.length/2];
    ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);

    return shorts;
}

以及write命令:

for (int i = 0; i < inputByteArray.length; i++)
        {
            outFile.writeShort(inputByteArray[i]);
        }

我会清理的,但那是问题所在。我的音频现在是正确的。

相关问题