【问题标题】:How can I check if a WAV file is valid/not corrupted如何检查 WAV 文件是否有效/未损坏
【发布时间】:2021-09-04 01:45:39
【问题描述】:

我将 node.js 与 typescript 一起用于接收 WAV 文件的服务器,我正在尝试检查 WAV 文件是否有效,但是我不确定最好的方法是什么,我已经知道如何检查一些事情,但我不确定我做的不对,可能正在做一些不需要的检查,并且可能遗漏了一些东西。

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
}

很多 cmets,因为我不熟悉使用 wav 文件和缓冲区

【问题讨论】:

    标签: javascript node.js typescript wav


    【解决方案1】:

    您可以为此使用特定的软件包。

    以这个为例:wav-file-info

    安装:

    npm install wav-file-info --save
    

    使用它:

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

    返回文件的数据或错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 2017-09-28
      相关资源
      最近更新 更多