A
A
Alexander Rakhmaev2019-10-24 14:51:50
Audio
Alexander Rakhmaev, 2019-10-24 14:51:50

Why is there a write delay (Waveform Audio Win32 API)?

I am using the Waveform Audio Win32 API.
I want to record sound from a microphone.

Here is the code:

WAVEFORMATEX _wfex;
_wfex.wFormatTag = WAVE_FORMAT_PCM;
_wfex.nChannels = 1;
_wfex.wBitsPerSample = 16;
_wfex.nSamplesPerSec = 44100;
_wfex.nBlockAlign = _wfex.nChannels * _wfex.wBitsPerSample / 8;
_wfex.nAvgBytesPerSec = _wfex.nSamplesPerSec * _wfex.nBlockAlign;
_wfex.cbSize = 0;
UINT myDevice = WAVE_MAPPER;
waveInOpen(&_hWaveIn, myDevice, &_wfex, 0L, 0L, WAVE_FORMAT_DIRECT);


int N = _wfex.nSamplesPerSec * 1 * t_seconds;

short int * buffer = new short int[N];
WAVEHDR WaveHdr;
WaveHdr.lpData = (LPSTR)buffer;
WaveHdr.dwBufferLength = N * 2;
WaveHdr.dwBytesRecorded = 0;
WaveHdr.dwUser = 0L;
WaveHdr.dwFlags = 0L;
WaveHdr.dwLoops = 0L;
waveInPrepareHeader(_hWaveIn, &WaveHdr, sizeof(WAVEHDR));
while (WaveHdr.dwFlags != WHDR_PREPARED);

waveInAddBuffer(_hWaveIn, &WaveHdr, sizeof(WAVEHDR));
waveInStart(_hWaveIn);
while (waveInUnprepareHeader(_hWaveIn, &WaveHdr, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING);
waveInClose(_hWaveIn);

WAVHEADER wh;
memcpy(wh.RIFF, "RIFF", 4);
wh.bytes = N * 2 + 36;
memcpy(wh.WAVE, "WAVE", 4);
memcpy(wh.fmt, "fmt ", 4);
wh.siz_wf = 16;
wh.wFormatTag = WAVE_FORMAT_PCM;
wh.nChannels = _wfex.nChannels;
wh.nSamplesPerSec = _wfex.nSamplesPerSec;
wh.nAvgBytesPerSec = _wfex.nAvgBytesPerSec;
wh.nBlockAlign = _wfex.nBlockAlign;
wh.wBitsPerSample = _wfex.wBitsPerSample;
memcpy(wh.data, "data", 4);
wh.pcmbytes = N * 2 * 1;

HANDLE hFile = CreateFile((LPCWSTR)L"audio.wav", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile)
{
  DWORD dwWrite;
  WriteFile(hFile, &wh, sizeof(WAVHEADER), &dwWrite, NULL);
  WriteFile(hFile, WaveHdr.lpData, WaveHdr.dwBufferLength, &dwWrite, NULL);
  CloseHandle(hFile);
  std::cout << "File was created\n";
}
else {
  std::cout << "File not created\n";
}


It writes well, but there is a delay of about 100 ms (see the figure below)
5db18f6bacfa8969438234.jpeg
This is critical in my application. In this regard, two questions:
1. Is it curable?
2. Is it possible to get data from a sound card not in an array, but in one discrete value? If I use the code above for an array of one element, then the first 100ms there is a value of 0.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Rakhmaev, 2019-11-05
@rahmaevao

I also noticed that these 100 ms are not a solid zero.
then 0 then 1, and before the pure signal goes, the noise increases. The last 25 samples grow in amplitude up to a value of 300.
Maybe this is somehow connected with some keys on the sound card?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question