javascript - Hur kan jag kontrollera om en WAV-fil är giltig/inte korrupt


Jag använder node.js med TypeScript för en server som tar emot WAV-filer och jag försöker kontrollera om en WAV-fil är giltig, men jag är inte säker på exakt hur det bästa sättet att göra det skulle vara. Jag har listat ut hur man kontrollerar några saker, men jag är inte säker på att jag inte gör det fel och kanske utför några onödiga kontroller och troligen missar något.

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
}

många kommentarer eftersom jag är ovan vid att arbeta med wav-filer och buffertar

Svar #1

Du skulle kunna använda ett specifikt paket för det.

Som ett exempel detta: wav-fil-info

Installation :

npm install wav-file-info --save

Använda det med:

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

Det returnerar filens data eller fel