Пример #1
0
//the entry point of our application
int main(int argc, char **argv)
{
    // generate the stereo whitenoise offset effect
    {
        // sound format parameters
        const int c_sampleRate = 44100;
        const int c_numSeconds = 4;
        const int c_numChannels = 2;
        const int c_numSamples = c_sampleRate * c_numChannels * c_numSeconds;

        // make space for our samples
        std::vector<float> samples;
        samples.resize(c_numSamples);

        // generate samples
        GenerateSamples(samples, c_sampleRate);

        // convert from float to the final format
        std::vector<int32> samplesInt;
        ConvertFloatSamples(samples, samplesInt);

        // write our samples to a wave file
        WriteWaveFile("stereonoise.wav", samplesInt, c_numChannels, c_sampleRate);
    }
}
Пример #2
0
void Upsampler::test()
{
    //
    // Make some audio data
    //
    int sampleRate = 48000;
    FrequencySweepAudioSource generator;
    AudioSampleBuffer sourceBuffer(1, sampleRate * 2);
    AudioSourceChannelInfo asi(&sourceBuffer, 0, sourceBuffer.getNumSamples());
    
    generator.prepareToPlay(sourceBuffer.getNumSamples(), sampleRate);
    generator.getNextAudioBlock(asi);
    generator.releaseResources();

    //
    // Create the upsampler
    //
    int const upsampleFactor = 4;
    Upsampler upsampler(sampleRate, sampleRate * upsampleFactor, 2.0);
    HeapBlock<double> upsamplerInputBuffer, upsamplerOutputBuffer;
    int upsamplerOutputBufferSamples = sourceBuffer.getNumSamples() * upsampleFactor * 2;
    
    upsamplerInputBuffer.allocate(sourceBuffer.getNumSamples(), true);
    upsamplerOutputBuffer.allocate(upsamplerOutputBufferSamples, true);
    
    //
    // Convert data to doubles
    //
    const float* source = sourceBuffer.getReadPointer(0);
    for (int i = 0; i < sourceBuffer.getNumSamples(); ++i)
    {
        upsamplerInputBuffer[i] = source[i];
    }
    
    //
    // Upsample
    //
    int upsampledCount = upsampler.upsample( upsamplerInputBuffer,
                                            upsamplerOutputBuffer,
                                            sourceBuffer.getNumSamples(),
                                            upsamplerOutputBufferSamples);
    
    //
    // Convert upsampled data to float
    //
    AudioSampleBuffer finalBuffer(1, upsamplerOutputBufferSamples);
    
    float *destination = finalBuffer.getWritePointer(0);
    for (int i = 0; i < upsampledCount; ++i)
    {
        destination[i] = (float)upsamplerOutputBuffer[i];
    }
    
    WriteWaveFile("upsample.wav", sampleRate * upsampleFactor, &finalBuffer, upsamplerOutputBufferSamples);
}
Пример #3
0
//
//  Write the captured wave data to an output file so that it can be examined later.
//
void SaveWaveData(BYTE *CaptureBuffer, size_t BufferSize, const WAVEFORMATEX *WaveFormat, const String &Filename)
{
    HANDLE waveHandle = CreateFile(Filename.CString(), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 
        NULL);
    if (waveHandle != INVALID_HANDLE_VALUE)
    {
        bool Success = WriteWaveFile(waveHandle, CaptureBuffer, BufferSize, WaveFormat);
        PersistentAssert(Success, "WriteWaveFile failed");
        CloseHandle(waveHandle);
    }
}
Пример #4
0
bool PhaseTest::calc(OwnedArray<AudioSampleBuffer> &buffs,String &msg, ErrorCodes &errorCodes)
{
	int i,num_samples;
	float last,peak,jump;
    float const *data = buffs[input]->getReadPointer(0);
	num_samples = buffs[input]->getNumSamples();

	peak = 0.0f;
	jump = 0.0f;

	for (i = 0; i < num_samples; i++)
	{
        float sample = fabs(data[i]);
		peak = jmax(peak, sample);
	}
	
	if (peak < 0.008)
	{
		msg = String::formatted(T("Phase "));
		msg += String::formatted(T(": level too low (peak %f)"),peak);

	}
	else
	{
		last = 0.0f;
		for(i = 0; i < num_samples; i++)
		{
			if (fabs(data[i] - last) > fabs(jump))
				jump = data[i] - last;
			last = data[i];
		}
		if(jump < 0.0f)
			msg = String::formatted(T("Phase test : Normal"));
		else
			msg = String::formatted(T("Phase test : Inverted"));
	}

#if WRITE_WAVE_FILES
	String name;

	name = String::formatted(T("Phase out%02d-in%02d.wav"),output,input);
	WriteWaveFile(unit, name, sample_rate, buffs[input], getSamplesRequired());
#endif

	if(pass_threshold_db > 0.0f)
		return (jump < 0.0f);
	else
		return (jump > 0.0f);
}
Пример #5
0
		// use mFileName as the file name.
		bool PCMWave::SaveToFile()
		{
			ofstream outfile(mFileName, ios::binary);
			if (!outfile.good()) {
				mStatus = FileOpenError;
				return false;
			}
			WriteWaveFile(&outfile);
			outfile.close();
			if (mStatus == OK) {
				return true;		// write operation has worked.
			}
			else {
				return false;		// error occurred writing to the file.
			}
		} // end SaveToFile function.
//
//  Write the captured wave data to an output file so that it can be examined later.
//
void SaveWaveData(BYTE *CaptureBuffer, size_t BufferSize, const WAVEFORMATEX *WaveFormat)
{
    wchar_t waveFileName[MAX_PATH];
    HRESULT hr = StringCbCopy(waveFileName, sizeof(waveFileName), L"WASAPICaptureEventDriven-");
    if (SUCCEEDED(hr))
    {
        GUID testGuid;
        if (SUCCEEDED(CoCreateGuid(&testGuid)))
        {
            wchar_t *guidString;
            if (SUCCEEDED(StringFromCLSID(testGuid, &guidString)))
            {
                hr = StringCbCat(waveFileName, sizeof(waveFileName), guidString);
                if (SUCCEEDED(hr))
                {
                    hr = StringCbCat(waveFileName, sizeof(waveFileName), L".WAV");
                    if (SUCCEEDED(hr))
                    {
                        HANDLE waveHandle = CreateFile(waveFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 
                            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 
                            NULL);
                        if (waveHandle != INVALID_HANDLE_VALUE)
                        {
                            if (WriteWaveFile(waveHandle, CaptureBuffer, BufferSize, WaveFormat))
                            {
                                printf("Successfully wrote WAVE data to %S\n", waveFileName);
                            }
                            else
                            {
                                printf("Unable to write wave file\n");
                            }
                            CloseHandle(waveHandle);
                        }
                        else
                        {
                            printf("Unable to open output WAV file %S: %d\n", waveFileName, GetLastError());
                        }
                    }
                }
                CoTaskMemFree(guidString);
            }
        }
    }
}
Пример #7
0
void CDoc::KannadaConcatenate()
{
	int i,j,temp,Space=0,ind=0;
	BOOL flagpresent,flagnext;
	IIScHeader presenthead,nexthead;
	short int presentsignal[10000],nextsignal[10000],presentpitch[10000],nextpitch[10000];//*EndSignal;
	FILE *presentwave,*nextwave,*target,*missing;
	char present[100],next[100],prescan[100],nextscan[100];
	char Parse[100];
	char c;
	SizeOfSentance = 0;
	int i1=0;
	char p[20] = "parse1.iis";
	do
	{
		c = Path.GetAt(i1);
		if(c == '$')
			break;
		Parse[i1]=c;
		i1++;

	}while(c != '$');
	Parse[i1] = '\0';
	
	strcat(Parse,p);
	
	Parse[strlen(Parse)]= '\0';	
	char Missing[100];
	char M[20] = "missing.txt";
	i1=0;
	do
	{
		c = Path.GetAt(i1);
		if(c == '$')
			break;
		Missing[i1]=c;
		i1++;

	}while(c != '$');
	Missing[i1] = '\0';
	strcat(Missing,M);
	Missing[strlen(Missing)]= '\0';
	char X[100];
	//X=new char [100];
	char x1[20] = "x";
	i1=0;
	do
	{
		c = Path.GetAt(i1);
		if(c == '$')
			break;
		X[i1]=c;
		i1++;

	}while(c != '$');
	X[i1] = '\0';
	strcat(X,x1);
	X[strlen(X)]= '\0';

	CFile file;
	VERIFY(file.Open(Parse,CFile::modeRead));
	//parsed = fopen(Parse,"rt");
	missing = fopen(Missing,"at");
	target = fopen(X,"wb");
	int size=0;
	int duration = 0,Unit=1;
//	int len_present;
//	int pitchmark[300];
	//fscanf(parsed,"%s ",&prescan);
	file.Read(&prescan[0],sizeof(char));
	i=0;
	while(prescan[i] != ' ')
	{
		i++;
		file.Read(&prescan[i],sizeof(char));
	}
	prescan[i] = '\0';

	i1=0;
	do
	{
		c = Path.GetAt(i1);
		if(c == '$')
			break;
		present[i1]=c;
		i1++;

	}while(c != '$');
	present[i1] = '\0';
	strcat(present,prescan);
	int flag_checkdot=0;
	
	
	//TRACE(" \nCunitArray = %d",CUnitArray[ind]);
	while(1)
	{
		//fscanf(parsed,"%s ",&nextscan);
		file.Read(&nextscan[0],sizeof(char));
		i=0;
		while(nextscan[i] != ' ')
		{
			i++;
			file.Read(&nextscan[i],sizeof(char));
		}
		nextscan[i] = '\0';
		i1=0;
		next[i1]='\0';
		do
		{
			c = Path.GetAt(i1);
			if(c == '$')
				break;
			next[i1]=c;
			i1++;
	
		}while(c != '$');
		next[i1] = '\0';
		strcat(next,nextscan);
		Unit++;

		// Last Unit
		if(strcmp(nextscan,"y") == 0 || strcmp(nextscan,"x") == 0 || strcmp(nextscan,"xd") == 0 || strcmp(nextscan,"xq") == 0 || strcmp(nextscan,"xc") == 0 || strcmp(nextscan,"xd") == 0 ||strcmp(nextscan,"xe") == 0)
		{

			presentwave = fopen(present,"rb");
			if(presentwave == NULL)
			{
				TRACE(" \nNot Present - 1 **** %s" ,present);
				
			}
			else
			{
			
				fscanf(presentwave,"%s ",&presenthead.FileID);
				fscanf(presentwave,"%d ",&presenthead.junk);
				fscanf(presentwave,"%d ",&presenthead.junk1);
				fscanf(presentwave,"%u ",&presenthead.LanguageID);
				fscanf(presentwave,"%u ",&presenthead.BasicUnit);
				fscanf(presentwave,"%d ",&presenthead.DataLength);
				fscanf(presentwave,"%d ",&presenthead.AvgPitch);
				fscanf(presentwave,"%d ",&presenthead.LSegment);
				fscanf(presentwave,"%d ",&presenthead.RSegment);
				fscanf(presentwave,"%d\n",&presenthead.LengthofPitchMarks);
				//presentsignal = new short int [presenthead.DataLength];
				for(i=0;i<10000;i++)
					presentsignal[i]=0;
				for(i=0;i<1000;i++)
					presentpitch[i]=0;
				for(i=0;i<presenthead.DataLength;i++)
					fscanf(presentwave,"%d ",&presentsignal[i]);

				for(i=0;i<presenthead.LengthofPitchMarks;i++)
				{
					fscanf(presentwave,"%d ",&temp);
					presentpitch[temp] = 1;
				}
				//TRACE(" Unit = %d, CunitArray[ind] = %d",Unit,CUnitArray[ind]+1);
					for(i=presenthead.LSegment;i<presenthead.DataLength;i++)
						fwrite(&presentsignal[i],sizeof(short int),1,target);
					
					size = size+presenthead.DataLength-presenthead.LSegment;
					TRACE("Size in last = %d",size);
				
			}
			if(strcmp(nextscan,"y") == 0)
			{
				j=0;
				for(i=0;i<4000;i++)
					fwrite(&j,sizeof(short int),1,target);
				size=size+4000;
				break;
			}
			else if(strcmp(nextscan,"xd") == 0 || strcmp(nextscan,"xc") == 0 || strcmp(nextscan,"xq") == 0 || strcmp(nextscan,"xe") == 0)
			{
				strcpy(prescan,"x");
				Unit++;
				if( Unit == CUnitArray[ind]+1)
					ind++;
				
				j=0;
				if(strcmp(nextscan,"xc") == 0 )
				{
					for(i=0;i<4000;i++)
					fwrite(&j,sizeof(short int),1,target);
					size=size+4000;
				}
				else 
				{	
					
					if(flag_checkdot == 1)
					{
						flag_checkdot=0;
					
					}
					else
					{

						for(i=0;i<8000;i++)
							fwrite(&j,sizeof(short int),1,target);
						size=size+8000;
					}
					
				}
				//fscanf(parsed,"%s ",&nextscan);
				file.Read(&nextscan[0],sizeof(char));
				i=0;
				while(nextscan[i] != ' ')
				{
					i++;
					file.Read(&nextscan[i],sizeof(char));
				}
				nextscan[i] = '\0';
				i1=0;
				next[i1]='\0';
				do
				{
					c = Path.GetAt(i1);
					if(c == '$')
						break;
					next[i1]=c;
					i1++;
	
				}while(c != '$');
				next[i1] = '\0';
				strcat(next,nextscan);
				if(strcmp(nextscan,"y") == 0)
					break;
				continue;
			}
			else
			{
				strcpy(present,next);
				strcpy(prescan,nextscan);
				continue;
			}
			if(presentwave != NULL)
				fclose(presentwave);
		}

		// First Unit
		if(strcmp(prescan,"x") == 0)
		{

			j=0;
			
			for(i=0;i<0;i++)
				fwrite(&j,sizeof(short int),1,target);
			size=size+0;
			strcpy(present,next);
			strcpy(prescan,nextscan);
			presentwave = fopen(present,"rb");
			if(presentwave == NULL)
			{
				fprintf(missing,"\n%s",present);
				TRACE("\n Not Present  - 2 ****** %s", present);
					
			
			}
			else
			{
				flag_checkdot=1;
				fscanf(presentwave,"%s ",&presenthead.FileID);
				fscanf(presentwave,"%d ",&presenthead.junk);
				fscanf(presentwave,"%d ",&presenthead.junk1);
				fscanf(presentwave,"%u ",&presenthead.LanguageID);
				fscanf(presentwave,"%u ",&presenthead.BasicUnit);
				fscanf(presentwave,"%d ",&presenthead.DataLength);
				fscanf(presentwave,"%d ",&presenthead.AvgPitch);
				fscanf(presentwave,"%d ",&presenthead.LSegment);
				fscanf(presentwave,"%d ",&presenthead.RSegment);
				fscanf(presentwave,"%d\n",&presenthead.LengthofPitchMarks);
				//presentsignal = new short int [presenthead.DataLength];
				//presentpitch = new short int [presenthead.DataLength];
				for(i=0;i<10000;i++)
					presentsignal[i]=0;
				for(i=0;i<10000;i++)
					presentpitch[i]=0;
				for(i=0;i<presenthead.DataLength;i++)
					fscanf(presentwave,"%d ",&presentsignal[i]);

				if(presenthead.BasicUnit != 1 || presenthead.BasicUnit != 3 || presenthead.BasicUnit != 7)
				{
					//delete [] PM ;
					//PM = new short int [100000];
						for(i=0;i<presenthead.LSegment;i++)
							fwrite(&presentsignal[i],sizeof(short int),1,target);
						size = size+presenthead.LSegment;
						//TRACE("\n Size in first = %d",size);
					
					
				}
			}
			strcpy(present,next);
			strcpy(prescan,nextscan);
			if(presentwave != NULL)
				fclose(presentwave);
			continue;
		}
		
		//Middle Unit

		if(strcmp(prescan,"x") != 0 && strcmp(nextscan,"x") != 0 && strcmp(prescan,"y") != 0 && strcmp(nextscan,"y") != 0)
		{
			
			presentwave = fopen(present,"rb");
			if(presentwave == NULL)
			{
				fprintf(missing,"\n%s",present);
				TRACE("\n Not Present - 3 ******** %s", present);
			
				flagpresent = 0;
			}
			else
			{
			
				flag_checkdot=0;
				flagpresent = 1;				
				fscanf(presentwave,"%s ",&presenthead.FileID);
				fscanf(presentwave,"%d ",&presenthead.junk);
				fscanf(presentwave,"%d ",&presenthead.junk1);
				fscanf(presentwave,"%u ",&presenthead.LanguageID);
				fscanf(presentwave,"%u ",&presenthead.BasicUnit);
				fscanf(presentwave,"%d ",&presenthead.DataLength);
				fscanf(presentwave,"%d ",&presenthead.AvgPitch);
				fscanf(presentwave,"%d ",&presenthead.LSegment);
				fscanf(presentwave,"%d ",&presenthead.RSegment);
				fscanf(presentwave,"%d\n",&presenthead.LengthofPitchMarks);
				//presentsignal = new short int [presenthead.DataLength];
				//presentpitch = new short int [presenthead.DataLength];
				for(i=0;i<10000;i++)
					presentsignal[i]=0;
				for(i=0;i<10000;i++)
					presentpitch[i]=0;
				for(i=0;i<presenthead.DataLength;i++)
					fscanf(presentwave,"%d ",&presentsignal[i]);

				for(i=0;i<presenthead.LengthofPitchMarks;i++)
				{
					fscanf(presentwave,"%d ",&temp);
					presentpitch[temp] = 1;
				}
			}

			nextwave = fopen(next,"rb");
			if(nextwave == NULL)
			{
				fprintf(missing,"\n%s",next);
				TRACE("\n Not Present - 4 ******** %s", next);
			
				flagnext=0;
			}
			else
			{
				flagnext=1;
				fscanf(nextwave,"%s ",&nexthead.FileID);
				fscanf(nextwave,"%d ",&nexthead.junk);
				fscanf(nextwave,"%d ",&nexthead.junk1);
				fscanf(nextwave,"%u ",&nexthead.LanguageID);
				fscanf(nextwave,"%u ",&nexthead.BasicUnit);
				fscanf(nextwave,"%d ",&nexthead.DataLength);
				fscanf(nextwave,"%d ",&nexthead.AvgPitch);
				fscanf(nextwave,"%d ",&nexthead.LSegment);
				fscanf(nextwave,"%d ",&nexthead.RSegment);
				fscanf(nextwave,"%d\n",&nexthead.LengthofPitchMarks);

				//nextsignal = new short int [nexthead.DataLength];
				//nextpitch = new short int [nexthead.DataLength];
				for(i=0;i<10000;i++)
					nextsignal[i]=0;
				for(i=0;i<10000;i++)
					nextpitch[i]=0;
				
				for(i=0;i<nexthead.DataLength;i++)
					fscanf(nextwave,"%d ",&nextsignal[i]);
				
				for(i=0;i<nexthead.LengthofPitchMarks;i++)
				{
					fscanf(nextwave,"%d ",&temp);
					nextpitch[temp] = 1;
				}
			}


			strcpy(ToDuration,present);
			
			int duration = DetectDuration();
			int tempduration=0;
		

			if(flagpresent == 1)
			{
		
				if(presenthead.BasicUnit == 2)
				{
					
					if(duration/2 < presenthead.DataLength-presenthead.LSegment)
						tempduration = duration/2;
					else 
						tempduration = presenthead.DataLength-presenthead.LSegment;
					
					i=0;
					while(1)
					{
						if(presentpitch[i] ==1 && i>presenthead.LSegment+tempduration)
						{
							tempduration=i-presenthead.LSegment;
							break;
						}
						i++;
						//Modified by me
						if(i >= presenthead.DataLength/2)
							break;
					}
					
						for(i=presenthead.LSegment;i<presenthead.LSegment+tempduration;i++)
							fwrite(&presentsignal[i],sizeof(short int),1,target);
						size = size+tempduration;
						TRACE("\n Size in middle = %d",size);
						
				}
				
				if(presenthead.BasicUnit == 4 || presenthead.BasicUnit == 5 || presenthead.BasicUnit == 6)
				{
				
					
						for(i=presenthead.LSegment;i<presenthead.RSegment;i++)
							fwrite(&presentsignal[i],sizeof(short int),1,target);
						size = size+presenthead.RSegment-presenthead.LSegment;
					
					
					if(duration/2 < presenthead.DataLength-presenthead.RSegment)
						tempduration = duration/2;
					else 
						tempduration = presenthead.DataLength-presenthead.RSegment;

					i=0;
					while(1)
					{
						if(presentpitch[i] ==1 && i>presenthead.RSegment+tempduration)
						{
							tempduration=i-presenthead.RSegment;
							break;
						}
						i++;
					}
				
					
						for(i=presenthead.RSegment;i<presenthead.RSegment+tempduration;i++)
							fwrite(&presentsignal[i],sizeof(short int),1,target);
						size = size+tempduration;
						TRACE("\n Size in middle = %d",size);
					
					
				}
				flagpresent=0;
			}
			tempduration=0;
			if(flagnext == 1)
			{
				if(duration/2 < nexthead.LSegment)
					tempduration = duration/2;
				else 
					tempduration = nexthead.LSegment;
						
				i=0;
				while(1)
				{
					if(nextpitch[i] ==1 && i>nexthead.LSegment-tempduration)
					{
						tempduration=nexthead.LSegment-i;
						break;
					}
					i++;
				}
				
					for(i=nexthead.LSegment-tempduration;i<nexthead.LSegment;i++)
						fwrite(&nextsignal[i],sizeof(short int),1,target);
					size = size+tempduration;
					//TRACE("\n Size in middle next  = %d",size);
				
				flagnext=0;
			}
			//TRACE("CSpace = %d, Cunit = %d, Unit = %d\n",CSpace[ind],CUnitArray[ind],Unit);
			strcpy(present,next);
			strcpy(prescan,nextscan);
			if(presentwave != NULL)
				fclose(presentwave);
			if(nextwave != NULL)
				fclose(nextwave);
			
		}
	}
	SizeOfSentance =  size;
	fcloseall();
	//TRACE("\n Space = %d, Unit = %d",Space,Unit);
	TRACE("\nOut of Concatenate %d\n",SizeOfSentance);
	WriteWaveFile();


}
Пример #8
0
TESTPROCAPI AudioRec_E2E(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE)
{
	MMRESULT mr;
    PBYTE pBufferBits;
    DWORD dwBufferSize;
	DWORD dwDuration = 5 * 1000;    // record for 5 seconds
    DWORD dwChannels = 2;           // default to mono
    DWORD dwBitsPerSample = 16;     // default to 16-bit samples
    DWORD dwSampleRate = 11025;     // default to 11.025KHz sample rate
    DWORD dwDeviceId = WAVE_MAPPER;           // capture from any available device
    WAVEFORMATEX wfx;
    PWAVEFORMATEX pwfx;
	DWORD dwSlop;
    DWORD dwWait;  
	int user_ret;
	HWND hWnd1;
	HANDLE hThread;
	DWORD IDThreadKey;

    // The shell doesn't necessarily want us to execute the test. Make sure
    // first.
    if(uMsg != TPM_EXECUTE)
    {
        return TPR_NOT_HANDLED;
    }

	pwfx=(PWAVEFORMATEX)&wfx;
    pwfx->cbSize = 0;
    pwfx->wFormatTag = WAVE_FORMAT_PCM;
    pwfx->wBitsPerSample = (WORD) dwBitsPerSample;
    pwfx->nSamplesPerSec = dwSampleRate;
    pwfx->nChannels = (WORD) dwChannels;
    pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample / 8;
    pwfx->nAvgBytesPerSec = pwfx->nBlockAlign * pwfx->nSamplesPerSec;


	 fail_log = 0;
    // compute the size of the capture buffer
    dwBufferSize = (DWORD)((((UINT64)dwDuration) * ((UINT64)pwfx->nAvgBytesPerSec) / 1000));

    // Pad out to a multiple of nBlockAlign
    dwBufferSize += dwBufferSize % pwfx->nBlockAlign;

	hWnd1 = GetForegroundWindow();
	MessageBox(hWnd1,TEXT("Please plug in loop back audio cable to [Headphone jack] and [Line in jack] then press ok button to record. "),TEXT("AudioRec_E2E"),MB_OK);

    // let user know what's going on
    RETAILMSG(1, (TEXT("Recording %5d ms to \"%s\": %c%02d %5dHz (%8d bytes)\r\n")
        , dwDuration
        , TEXT(AUDIO_SD_REC_PATH)
        , pwfx->nChannels == 2 ? L'S' : L'M'
        , pwfx->wBitsPerSample
        , pwfx->nSamplesPerSec
        , dwBufferSize
        ));


	hThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ThreadProc_AudioPlayThread, NULL, 0,&IDThreadKey);
    // try to allocate the capture buffer
    pBufferBits = new BYTE [dwBufferSize];
    if (pBufferBits == NULL) {
        RETAILMSG (1, (TEXT("Unable to allocate %d bytes for %d ms of audio data\r\n"), dwBufferSize, dwDuration));
        return MMSYSERR_NOMEM;
    }
    WAVEHDR hdr;
    memset(&hdr, 0, sizeof(WAVEHDR));
    hdr.dwBufferLength = dwBufferSize;
    hdr.lpData = (char *) pBufferBits;

    mr = RecordWaveBuffer(&hdr, dwDeviceId, pwfx, dwDuration);
    MRCHECK(mr, RecordWaveBuffer,ERROR_OPEN);

    // finally, write the captured buffer to the file
    // note that we use hdr.dwBytesRecorded, not dwBuffersize.
    RETAILMSG(1, (TEXT("Capture completed. Writing %s\r\n"), TEXT(AUDIO_SD_REC_PATH)));
    mr = WriteWaveFile(TEXT(AUDIO_SD_REC_PATH), pwfx, hdr.dwBytesRecorded, pBufferBits);
    MRCHECK(mr, WriteWaveFile,ERROR_OPEN);


    // Play
	pBufferBits = NULL;
    pwfx = NULL;

	
	MessageBox(hWnd1,TEXT("Please remove loop back audio cable and plug in headphone or speaker to your device. "),TEXT("AudioRec_E2E"),MB_OK);

    HANDLE hevDone = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (hevDone == NULL) {
        return MMSYSERR_NOMEM;
    }

    mr = ReadWaveFile(TEXT(AUDIO_SD_REC_PATH),&pwfx,&dwBufferSize,&pBufferBits);
    MRCHECK(mr, ReadWaveFile, ERROR_READ);

    // Note: Cast to UINT64 below is to avoid potential DWORD overflow for large (>~4MB) files.
    dwDuration = (DWORD)(((UINT64)dwBufferSize) * 1000 / pwfx->nAvgBytesPerSec);

    RETAILMSG(1, (TEXT("\"%s\" %c%02d %5dHz %6d bytes %5d ms\r\n")
        , TEXT(AUDIO_SD_REC_PATH)
        , pwfx->nChannels == 2 ? L'S' : L'M'
        , pwfx->wBitsPerSample
        , pwfx->nSamplesPerSec
        , dwBufferSize
        , dwDuration
        ));

    HWAVEOUT hwo;
    mr = waveOutOpen(&hwo, WAVE_MAPPER, pwfx, (DWORD) hevDone, NULL, CALLBACK_EVENT);
    MRCHECK(mr, waveOutOpen, ERROR_OPEN);

    
    memset(&hdr, 0, sizeof(hdr));
    hdr.dwBufferLength = dwBufferSize;
    hdr.lpData = (char *) pBufferBits;

    mr = waveOutPrepareHeader(hwo, &hdr, sizeof(hdr));
    MRCHECK(mr, waveOutPrepareHeader, ERROR_PLAY);

    mr = waveOutWrite(hwo, &hdr, sizeof(hdr));
    MRCHECK(mr, waveOutWrite, ERROR_PLAY);

    // wait for play + 1 second slop
    dwSlop = 1000;
    dwWait = WaitForSingleObject(hevDone, dwDuration + dwSlop);
    if (dwWait != WAIT_OBJECT_0) {
        // not much to here, other than issue a warning        
		g_pKato->Log(LOG_COMMENT, TEXT("Timeout waiting for playback to complete."));
    }

    mr = waveOutUnprepareHeader(hwo, &hdr, sizeof(hdr));
    MRCHECK(mr, waveOutUnprepareHeader, ERROR_PLAY);
	user_ret = MessageBox(hWnd1, (LPCWSTR)L"Do you hear the sound playing correctly?", 
					(LPCWSTR)L"AudioRec_E2E", MB_YESNO);		
	if( user_ret != IDYES ){
		g_pKato->Log(LOG_COMMENT, TEXT("User reported the sound playing failed!."));
		fail_log ++;
	}

ERROR_PLAY:
    mr = waveOutClose(hwo);
    MRCHECK(mr, waveOutClose, ERROR_OPEN);

ERROR_OPEN:
    delete [] pBufferBits;
    delete [] pwfx;

ERROR_READ:
	if(hevDone !=NULL)
	{
      CloseHandle(hevDone);
	}
    if(hThread !=NULL)
	{
		CloseHandle(hThread);
	}
    if( hWnd1 != NULL  ) 
	{
		CloseHandle(hWnd1);
	}
    return ((fail_log == 0)? TPR_PASS:TPR_FAIL);	
	
}