import 'dart:io';

class PcmWavConverter {
  static convert(File pcmFile, File wavFile, int sampleRate, int channels,
      int bitDepth) {
    int dataLength = pcmFile.lengthSync();
    List<int> wavHeader = _createWavHeader(dataLength, sampleRate, channels, bitDepth);
    wavFile.writeAsBytesSync(wavHeader, mode: FileMode.write);
    wavFile.writeAsBytesSync(pcmFile.readAsBytesSync(), mode: FileMode.append);
  }

  static List<int> _createWavHeader(int dataLength, int sampleRate,
      int channels, int bitDepth) {
    int byteRate = sampleRate * channels * bitDepth ~/ 8;
    int wavSize = dataLength + 36;
    List<int> header = List<int>.filled(44, 0);
    header[0] = 'R'.codeUnitAt(0);
    header[1] = 'I'.codeUnitAt(0);
    header[2] = 'F'.codeUnitAt(0);
    header[3] = 'F'.codeUnitAt(0);
    header[4] = wavSize & 0xff;
    header[5] = ((wavSize) >> 8) & 0xff;
    header[6] = ((wavSize) >> 16) & 0xff;
    header[7] = ((wavSize) >> 24) & 0xff;
    header[8] = 'W'.codeUnitAt(0);
    header[9] = 'A'.codeUnitAt(0);
    header[10] = 'V'.codeUnitAt(0);
    header[11] = 'E'.codeUnitAt(0);
    header[12] = 'f'.codeUnitAt(0);
    header[13] = 'm'.codeUnitAt(0);
    header[14] = 't'.codeUnitAt(0);
    header[15] = ' '.codeUnitAt(0);
    header[16] = 16;
    header[17] = 0;
    header[18] = 0;
    header[19] = 0;
    header[20] = 1;
    header[21] = 0;
    header[22] = channels & 0xff;
    header[23] = (channels >> 8) & 0xff;
    header[24] = sampleRate & 0xff;
    header[25] = (sampleRate >> 8) & 0xff;
    header[26] = (sampleRate >> 16) & 0xff;
    header[27] = (sampleRate >> 24) & 0xff;
    header[28] = byteRate & 0xff;
    header[29] = (byteRate >> 8) & 0xff;
    header[30] = (byteRate >> 16) & 0xff;
    header[31] = (byteRate >> 24) & 0xff;
    header[32] = (channels * bitDepth ~/ 8) & 0xff;
    header[33] = 0;
    header[34] = bitDepth;
    header[35] = 0;
    header[36] = 'd'.codeUnitAt(0);
    header[37] = 'a'.codeUnitAt(0);
    header[38] = 't'.codeUnitAt(0);
    header[39] = 'a'.codeUnitAt(0);
    header[40] = dataLength & 0xff;
    header[41] = (dataLength >> 8) & 0xff;
    header[42] = (dataLength >> 16) & 0xff;
    header[43] = (dataLength >> 24) & 0xff;
    return header;
  }
}
