Calculating the Duration of a WAV Sound

The length of time for which a waveform will play is determined by the data size and the format. The data size and format can be retrieved by using the CWaveFile::GetSize and CWaveFile::GetFormat methods in the DirectSound samples.

The following example function returns the duration of a WAV file, in milliseconds:

DWORD GetSoundLength(LPSTR strFileName)
{
  CWaveFile* pWav;
  DWORD dwLen = 0;
  DWORD dwSize;
  WAVEFORMATEX* wfx;
 
  pWav = new CWaveFile();
  if (SUCCEEDED(pWav->Open(strFileName, NULL, WAVEFILE_READ)))
  {
    wfx = pWav->GetFormat();
    dwSize = pWav->GetSize();
    dwLen = (DWORD) (1000 * dwSize / wfx->nAvgBytesPerSec);
    pWav->Close();
  }
  if (pWav) delete pWav;
  return dwLen;
}

See Also

CWaveFile Sample Class, DirectSound Sample Utility Classes, Reading WAV Data