Android:Creating Wave file using Raw PCM, the wave file does not play

依然范特西╮ 提交于 2019-12-03 21:26:03
Robert Rowntree

try the following code:

private void rawToWave(final File rawFile, final File waveFile) throws IOException {

    byte[] rawData = new byte[(int) rawFile.length()];
    DataInputStream input = null;
    try {
        input = new DataInputStream(new FileInputStream(rawFile));
        input.read(rawData);
    } finally {
        if (input != null) {
            input.close();
        }
    }

    DataOutputStream output = null;
    try {
        output = new DataOutputStream(new FileOutputStream(waveFile));
        // WAVE header
        // see http://ccrma.stanford.edu/courses/422/projects/WaveFormat/
        output.writeChars("RIFF"); // chunk id
        output.writeInt(36 + rawData.length); // chunk size
        output.writeChars("WAVE"); // format
        output.writeChars("fmt "); // subchunk 1 id
        output.writeInt(16); // subchunk 1 size
        output.writeShort((short) 1); // audio format (1 = PCM)
        output.writeShort((short) 1); // number of channels
        output.writeInt(SAMPLE_RATE); // sample rate
        output.writeInt(SAMPLE_RATE * 2); // byte rate
        output.writeShort((short) 2); // block align
        output.writeShort((short) 16); // bits per sample
        output.writeChars(output, "data"); // subchunk 2 id
        output.writeInt(output, rawData.length); // subchunk 2 size
        // Audio data (conversion big endian -> little endian)
        short[] shorts = new short[rawData.length / 2];
        ByteBuffer.wrap(rawData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
        ByteBuffer bytes = ByteBuffer.allocate(shorts.length * 2);
        for (short s : shorts) {
            bytes.putShort(s);
        }
        output.write(bytes.array());
    } finally {
        if (output != null) {
            output.close();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!