Java pcm格式的音频实现8位和16位互转

    技术2022-07-10  104

      //将16位pcm数据转换成8位有符号的pcm

                    byte[] readBuffer = new byte[4096];                 byte[] sendBuffer = new byte[readBuffer.length / 2];                 for (int i = 0; i<readBuffer.length; i += 2) {                     if ((readBuffer[i + 1] & 0x80) == 0x80) {                         sendBuffer[i / 2] = (byte) (readBuffer[i + 1] & 0x7f);                     } else {                         sendBuffer[i / 2] = (byte) (readBuffer[i + 1] + 0x80);                     }

                    }

     

                    //将8位有符号的的pcm数据转换成16位

                    byte[] readBuffer = new byte[4096];                 int audioDataLen = readBuffer.length * 2;                 byte[] audioBuffer = new byte[readBuffer.length * 2];                                  for (int i = 0; i<readBuffer.length; i++) {                     /*if (readBuffer[i] == 63 && i != 0 && i != readBuffer.length - 1) {                         readBuffer[i] = (byte) ((readBuffer[i + 1] + readBuffer[i - 1]) / 2);                     }*/                     if ((readBuffer[i] & 0x80) == 0x80) {                         audioBuffer[2 * i] = 0x00;                         audioBuffer[2 * i + 1] = (byte) (readBuffer[i] - 0x80);                     } else {                         audioBuffer[2 * i] = (byte) 0xff;                         audioBuffer[2 * i + 1] = (byte) (readBuffer[i] - 0x80);                     }                 }

    Processed: 0.015, SQL: 9