How can I check if a WAV file is valid/not corrupted

I’m using node.js with typescript for a server which receives WAV files and I’m trying to check wether a WAV file is valid, however I’m not sure exactly how the best way to do it would be, I have figured out how to check a few things but I’m not sure that I’m not doing it correctly & may be doing a few unneeded checks and am probably missing something.

function isWavValid(fileBuffer: Buffer) {
  const byteRate = fileBuffer.readIntLE(28, 4);
  const numChannels = fileBuffer.readIntLE(22, 2);
  const sampleRate = fileBuffer.readIntLE(24, 4);
  const bitsPerSample = fileBuffer.readIntLE(34, 2);
  const reportedDataLength = fileBuffer.readIntLE(40, 4);
  const realDataLength = fileBuffer.slice(44).length;
  const reportedChunkSize = fileBuffer.readIntLE(4, 4);
  const reportedBlockAlign = fileBuffer.readIntLE(32, 2);

  if (fileBuffer.toString('utf8', 0, 4) !== 'RIFF') return false; // is the "RIFF" chunk ID "RIFF"
  if (fileBuffer.toString('utf8', 8, 12) !== 'WAVE') return false; // is the "RIFF" chunk format "WAVE"
  if (fileBuffer.toString('utf8', 12, 16) !== 'fmt ') return false; // is the "fmt " sub-chunk ID "fmt "
  if (fileBuffer.toString('utf8', 36, 40) !== 'data') return false; // is the "data" sub-chunk ID "data")
  if (reportedDataLength !== realDataLength) return false; // does the "data" sub-chunk length match the actual data length
  if (byteRate !== sampleRate * numChannels * bitsPerSample / 8) return false; // does the byterate from the "fmt " sub-chunk match calculated byterate from the samplerate, channel count and bits per sample (divided into bytes per sample)
  if (numChannels > 65535 || numChannels < 1) return false; // is the channel count within a valid range of min 1 and max 65535
  if (reportedChunkSize !== fileBuffer.length - 8) return false; // does the "RIFF" chunk size match the actual file size (minus the chunk ID and file size (8 bytes)
  if (reportedBlockAlign !== numChannels * bitsPerSample / 8) return false; // does the "fmt " chunk block align match the actual number of bytes for one sample

  return true

lots of comments because I’m unfamiliar with working with wav files & buffers


You could use an especific package for that.

As an example this one: wav-file-info


npm install wav-file-info --save

Using it with:

var wavFileInfo = require('wav-file-info');
wavFileInfo.infoByFilename('./test.wav', function(err, info){
  if (err) throw err;

It returns the data of the file or errors

Source: stackoverflow