When I record audio to a wav file,first time, the wave is all right.But from the second time, the wave become wrong.There is about 0.4s empty audio in the head of the wave.the code is like below.
FMOD_RESULT result;
unsigned int datalength = 0, soundlength;
FILE *fp;
uint length;
float volume;
bool mute;
m_result = system->init(32, FMOD_INIT_NORMAL, 0);
FMOD_CREATESOUNDEXINFO exinfo;
memset(&exinfo, 0, sizeof(FMOD_CREATESOUNDEXINFO));
exinfo.cbsize = sizeof(FMOD_CREATESOUNDEXINFO);
exinfo.numchannels = m_iChannels;
exinfo.format = FMOD_SOUND_FORMAT_PCM16;
exinfo.defaultfrequency = m_iSampleRate;
exinfo.length = exinfo.defaultfrequency * sizeof(short) * exinfo.numchannels;
result = system->createSound(0, FMOD_2D |FMOD_OUTPUTTYPE_WINMM| FMOD_OPENUSER, &exinfo, &sound);
result = system->recordStart(recorddriver, sound, true);
if (result != FMOD_OK)
{
emit sigDriveErr();
return;
}
fp = fopen(fileName.toStdString().c_str(), "wb");
if (!fp)
{
printf("ERROR : could not open record.wav for writing.\n");
return;
}
/*
Write out the wav header. As we don't know the length yet it will be 0.
*/
WriteWavHeader(fp, sound, datalength);
result = sound->getLength(&soundlength, FMOD_TIMEUNIT_PCM);
ERRCHECK(result);
QVector<float> waveData;
do
{
static unsigned int lastrecordpos = 0;
static unsigned int index = 0;
unsigned int recordpos = 0;
system->getRecordPosition(recorddriver, &recordpos);
ERRCHECK(result);
if (recordpos != lastrecordpos)
{
void *ptr1, *ptr2;
int blocklength;
unsigned int len1, len2;
blocklength = (int)recordpos - (int)lastrecordpos;
if (blocklength < 0)
{
blocklength += soundlength;
}
/*
Lock the sound to get access to the raw data.
*/
sound->lock(lastrecordpos * exinfo.numchannels * 2, blocklength * exinfo.numchannels * 2, &ptr1, &ptr2, &len1, &len2); /* * exinfo.numchannels * 2 = stereo 16bit. 1 sample = 4 bytes. */ /* Write it to disk.
*/
if (ptr1 && len1)
{
datalength += fwrite(ptr1, 1, len1, fp);
signed short *data = (signed short *)ptr1;
/*for (int i = 0, n = 0; i < len1; i += step, n++)
{
waveData.append(data[n]);
}
index++;
if (index % 5 == 0)
{
emit waveDataReceive(waveData);
waveData.clear();
}*/
}
if (ptr2 && len2)
{
datalength += fwrite(ptr2, 1, len2, fp);
ushort *data = (ushort *)ptr2;
//QVector<float> waveData;
/*for (int i = 0, n = 0; i < len1; i += step, n++)
{
waveData.append(data[n]);
}
index++;
if (index % 5 == 0)
{
emit waveDataReceive(waveData);
waveData.clear();
}*/
}
/*
Unlock the sound to allow FMOD to use it again.
*/
sound->unlock(ptr1, ptr2, len1, len2);
}
lastrecordpos = recordpos;
system->update();
Sleep(10);
} while (isStopWave != true);
WriteWavHeader(fp, sound, datalength);
fclose(fp);