• (2 Pages)
  • +
  • 1
  • 2

Sound Recorder using the low level Windows API in C++ Recorder with wave visualisation Rate Topic: -----

#16 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 810
  • View blog
  • Posts: 2,405
  • Joined: 20-March 10

Posted 27 July 2012 - 04:55 PM

Hi all,

It has been pointed out that I forgot
to add gdi32.lib to the list of libs for this Tutorial

Apologies..

Also I also think #include "resource.h"
should come first in the list of includes and not last as I seem to have them.

Snoopy.
Was This Post Helpful? 0
  • +
  • -

#17 lsanczyk  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 14-November 12

Posted 14 November 2012 - 03:43 PM

Hi Snoopy, i was having problems creating the VC++ project. Can you upload a rar/zip file with the entire solution? Thanks for your help!
Was This Post Helpful? 0
  • +
  • -

#18 shahzee  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 01-February 13

Posted 01 February 2013 - 10:34 AM

can you please place the compiled source code in a compressed file. I am having alot of errors . Also how to include Winmm.lib ? Thanks
Was This Post Helpful? 0
  • +
  • -

#19 shahzee  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 01-February 13

Posted 01 February 2013 - 10:45 AM

I am getting these errors . please help me to resolve these.

<code>
Error 1 error C2440: '=' : cannot convert from 'char [9]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 65 1 test
Error 2 error C2440: '=' : cannot convert from 'const char [9]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 76 1 test
Error 3 error C2664: 'CreateWindowExW' : cannot convert parameter 2 from 'char [9]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 121 1 test
Error 4 error C2664: 'CreateWindowExW' : cannot convert parameter 3 from 'const char [7]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 209 1 test
Error 5 error C2664: 'CreateWindowExW' : cannot convert parameter 3 from 'const char [5]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 211 1 test
Error 6 error C2664: 'CreateWindowExW' : cannot convert parameter 3 from 'const char [5]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 213 1 test
Error 7 error C2664: 'MessageBoxW' : cannot convert parameter 3 from 'char [9]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 401 1 test
Error 8 error C2440: '=' : cannot convert from 'const char [25]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 574 1 test
Error 9 error C2440: '=' : cannot convert from 'char [260]' to 'LPWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 576 1 test
Error 10 error C2440: '=' : cannot convert from 'const char [4]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 582 1 test
Error 11 error C2664: 'MessageBoxW' : cannot convert parameter 3 from 'char [9]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 652 1 test
Error 12 error C2664: 'MessageBoxW' : cannot convert parameter 3 from 'char [9]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 804 1 test
Error 13 error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'const char [16]' to 'LPCWSTR' c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 976 1 test
14 IntelliSense: a value of type "char *" cannot be assigned to an entity of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 65 25 test
15 IntelliSense: a value of type "const char *" cannot be assigned to an entity of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 76 24 test
16 IntelliSense: argument of type "char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 99 16 test
17 IntelliSense: argument of type "char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 101 16 test
18 IntelliSense: argument of type "const char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 209 21 test
19 IntelliSense: argument of type "const char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 211 21 test
20 IntelliSense: argument of type "const char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 213 21 test
21 IntelliSense: argument of type "char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 399 43 test
22 IntelliSense: a value of type "const char *" cannot be assigned to an entity of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 574 29 test
23 IntelliSense: a value of type "char *" cannot be assigned to an entity of type "LPWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 576 27 test
24 IntelliSense: a value of type "const char *" cannot be assigned to an entity of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 582 29 test
25 IntelliSense: argument of type "char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 650 47 test
26 IntelliSense: argument of type "char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 802 48 test
27 IntelliSense: argument of type "const char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 976 26 test
28 IntelliSense: argument of type "const char *" is incompatible with parameter of type "LPCWSTR" c:\users\shahzeb\documents\visual studio 2010\projects\audio streaming\audio streaming\recorder.cpp 976 61 test

</code>
Was This Post Helpful? 0
  • +
  • -

#20 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 810
  • View blog
  • Posts: 2,405
  • Joined: 20-March 10

Posted 03 February 2013 - 02:34 AM

Hi,

You are building this as a unicode build

this is not a Unicode build.

You need to change your charcter set to Multi-Byte

Snoopy.
Was This Post Helpful? 0
  • +
  • -

#21 shahzee  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 01-February 13

Posted 03 February 2013 - 02:43 AM

Hi Snoopy,

Thanks for your help . I figured out the problem myself. the code helped me alot.
Was This Post Helpful? 0
  • +
  • -

#22 Stela115  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-May 13

Posted 19 May 2013 - 06:45 AM

Hello snoopy11!
I have done exactly what you have asked us to,but there seems to be a problem :( I've put the error below and I was hoping if you could help me figure it out.I dont have much experience at c++,and I would appreciate it if you could help me :)

[1>------ Build started: Project: window, Configuration: Debug Win32 ------
1>Build started 19-May-13 3:34:25 PM.
1>InitializeBuildStatus:
1> Touching "Debug\window.unsuccessfulbuild".
1>ClCompile:
1> recorder.cpp
1> jkhbou.cpp
1>c:\users\user\desktop\window\window\jkhbou.cpp(195): error C2601: 'readSample' : local function definitions are illegal
1> c:\users\user\desktop\window\window\jkhbou.cpp(121): this line contains a '{' which has not yet been matched
1>c:\users\user\desktop\window\window\jkhbou.cpp(240): error C2601: 'Wav' : local function definitions are illegal
1> c:\users\user\desktop\window\window\jkhbou.cpp(121): this line contains a '{' which has not yet been matched
1>c:\users\user\desktop\window\window\jkhbou.cpp(386): error C2143: syntax error : missing ';' before 'case'
1>c:\users\user\desktop\window\window\jkhbou.cpp(573): error C2601: 'SaveWavFile' : local function definitions are illegal
1> c:\users\user\desktop\window\window\jkhbou.cpp(121): this line contains a '{' which has not yet been matched
1>c:\users\user\desktop\window\window\jkhbou.cpp(611): fatal error C1075: end of file found before the left brace '{' at 'c:\users\user\desktop\window\window\jkhbou.cpp(121)' was matched
1> Generating Code...
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.57
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========]
Was This Post Helpful? 0
  • +
  • -

#23 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 810
  • View blog
  • Posts: 2,405
  • Joined: 20-March 10

Posted 19 May 2013 - 09:36 AM

It seems like you have not copied the code

correctly and you have missing braces...

please post your code and I will take a look.

Regards

Snoopy.
Was This Post Helpful? 0
  • +
  • -

#24 chris_v  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-May 14

Posted 13 May 2014 - 07:00 AM

Hi Snoopy11,

first of all very nice job!! I'm newbie to programming, especially to c++ but your code is very understandable!

I use visual studio 2010 and windows XP, but I have the following errors..

1>------ Rebuild All started: Project: sound_record, Configuration: Debug Win32 ------
1>Build started 13/5/2014 4:36:12 μμ.
1>_PrepareForClean:
1>  Deleting file "Debug\sound_record.lastbuildstate".
1>InitializeBuildStatus:
1>  Creating "Debug\sound_record.unsuccessfulbuild" because "AlwaysCreate" was specified.
1>ClCompile:
1>  stdafx.cpp
1>  recorder.cpp
1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
1>C:\Documents and Settings\Sotiris\My Documents\Visual Studio 2010\Projects\sound_record\Debug\sound_record.exe : fatal error LNK1120: 1 unresolved externals
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:07.40
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========



In order to create the resource.rc file, I haven't selected empty project. So I have, apart from your files (resource.h, resource.rc, recorder.cpp) stdafx.h which includes
#pragma once

#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <windows.h>



targetver.h which includes
#pragma once

// Including SDKDDKVer.h defines the highest available Windows platform.

// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.

#include <SDKDDKVer.h>



and stdafx.cpp

#include "stdafx.h"




Also by default, in recorder.cpp was that part, which I delete and insert yours

#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
	return 0;
}



Have you got any idea how to solve that error?

Thank you very much!!
Best regards
Was This Post Helpful? 0
  • +
  • -

#25 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 810
  • View blog
  • Posts: 2,405
  • Joined: 20-March 10

Posted 13 May 2014 - 08:04 AM

If you have

#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
	return 0;
}


then you have selected a Win32 console application restart and select Win32 Project

this will start a Windows Project also you dont need stdafx.h its really quite useless.

Snoopy.
Was This Post Helpful? 0
  • +
  • -

#26 chris_v  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-May 14

Posted 14 May 2014 - 02:59 AM

Thank you very much snoopy11! That was the problem!!!

Well what I want to do now, is to capture also the timestamps of the data to a txt file, in order to synchronize the audio files from different computers. Here is what I tried to do in the recorder.cpp, but in the dump.txt file is it saved only one value..

// sound_record.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <CommDlg.h>
#include <MMSystem.h>
#include <fstream>
#include <cstdlib>
#include "resource.h"

using namespace std;
//Globals for sound wave visualistion
int number, length, byte_samp, byte_sec, bit_samp;
static int sampleRate = 11025;
const int NUMPTS = 11025 * 10;
bool mono = TRUE;
bool PLAY = FALSE;
errno_t wavfile;
char * filename;
int s_rate = 11025;
double limit = 10000.0;
FILE * stream;
/*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
/* Declare procedures */
int readSample(int number,bool leftchannel);
void SaveWavFile(char *FileName, PWAVEHDR WaveHeader);
void Wav(char *c, HWND hWnd);
/*  Make the class name into a global variable  */
char szAppName[ ] = "Recorder";



std::fstream m_filestream;
static bool once = true;
char timestamp[256];

char *time_stamp(){

    SYSTEMTIME stime;
    FILETIME ltime;
    FILETIME ftTimeStamp;
    char TimeStamp[256];
    GetSystemTimeAsFileTime(&ftTimeStamp); 

    FileTimeToLocalFileTime (&ftTimeStamp,&ltime);
    FileTimeToSystemTime(&ltime,&stime);

    sprintf(TimeStamp, "%04d%02d%02d%02d%02d%02d%03d", stime.wYear, stime.wMonth,stime.wDay, stime.wHour,stime.wMinute,stime.wSecond, 
            stime.wMilliseconds);
	return TimeStamp;
}



// **********
// Windows Main Function.
// - Here starts our program
int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nCmdShow)
{

    HWND hwnd;               /* This is the handle for our window */
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */

    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szAppName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = "APP_MENU";                 /*menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default colour as the background of the window */
    wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;

    /* The class is registered, let's create the program*/
    hwnd = CreateWindowEx (
               0,                   /* Extended possibilites for variation */
               szAppName,         /* Classname */
               szAppName,       /* Title Text */
               WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX, /* default window */
               CW_USEDEFAULT,       /* Windows decides the position */
               CW_USEDEFAULT,       /* where the window ends up on the screen */
               430,                 /* The programs width */
               300,                 /* and height in pixels */
               HWND_DESKTOP,        /* The window is a child-window to desktop */
               NULL,                /*use class menu */
               hThisInstance,       /* Program Instance handler */
               NULL                 /* No Window Creation data */
           );

    /* Make the window visible on the screen */
    ShowWindow (hwnd, nCmdShow);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL, 0, 0))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}



/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static HWND RecButton;
    static HWND PlyButton;
    static HWND StpButton;
    static HMENU hMenu;
    static HPEN hPen;
    static BOOL         bRecording, bPlaying,bEnding, bTerminating ;
    static DWORD        dwDataLength, dwRepetitions = 1 ;
    static HWAVEIN      hWaveIn ;
    static HWAVEOUT     hWaveOut ;
    static PBYTE        pBuffer1, pBuffer2, pSaveBuffer, pNewBuffer ;
    static PWAVEHDR     pWaveHdr1, pWaveHdr2 ;
    static TCHAR        szOpenError[] = TEXT ("Error opening waveform audio!");
    static TCHAR        szMemError [] = TEXT ("Error allocating memory!") ;
    static WAVEFORMATEX waveform ;

    hMenu = GetMenu (hwnd);
    HDC hDC;
    POINT pt [NUM];
    BOOL fSuccess = FALSE;


	if(once)
	{
		once = false;
		m_filestream.open("dump.txt", std::fstream::in | std::fstream::out | std::fstream::app);
	}


    switch (message)                  /* handle the messages */
    {
    case WM_CREATE:
        RecButton = CreateWindow ( TEXT ("button"),"RECORD",WS_VISIBLE|WS_CHILD|ES_LEFT|1,7,175,100,25,hwnd,(HMENU) IDC_RECORD,((LPCREATESTRUCT) lParam) -> hInstance,NULL);
        PlyButton = CreateWindow ( TEXT ("button"),"PLAY",WS_VISIBLE|WS_CHILD|ES_LEFT|1,157,175,100,25,hwnd,(HMENU) IDC_PLAY,((LPCREATESTRUCT) lParam) -> hInstance,NULL);
        StpButton = CreateWindow ( TEXT ("button"),"STOP",WS_VISIBLE|WS_CHILD|ES_LEFT|1,314,175,100,25,hwnd,(HMENU) IDC_STOP,((LPCREATESTRUCT) lParam) -> hInstance,NULL);
        EnableWindow (PlyButton, FALSE) ;
        EnableWindow (StpButton, FALSE)  ;

        pWaveHdr1 =  reinterpret_cast <PWAVEHDR> ( malloc (sizeof (WAVEHDR)) );
        pWaveHdr2 = reinterpret_cast <PWAVEHDR> ( malloc (sizeof (WAVEHDR)) ) ;
        // Allocate memory for save buffer

        pSaveBuffer = reinterpret_cast <PBYTE> ( malloc (1) ) ;
		 
        return 0;

    case WM_PAINT:
        PAINTSTRUCT 	ps;
        hDC = BeginPaint(hwnd, &ps);

        if (hDC)
        {
            RECT rc;
            rc.top = 35;
			rc.left = 0;
			rc.bottom = 145;
			rc.right = 425;
			FillRect(hDC,&rc,(HBRUSH)(COLOR_WINDOW+2));
            if (PLAY==TRUE)
            {
				FillRect(hDC,&rc,(HBRUSH)(COLOR_WINDOW+2));
                hPen = CreatePen(PS_SOLID,1,RGB(0,200,0));
                SelectObject(hDC, hPen);

                SetMapMode(hDC, MM_ISOTROPIC);
                SetWindowExtEx(hDC, 400, 300, NULL);
                SetViewportExtEx(hDC,200, 180, NULL);
                SetViewportOrgEx(hDC, 0, 0, NULL);

                int sample=0;
                int i=1;
                int num = 60000;
                sample= readSample(i, TRUE);
                // scale the sample

                pt[i].x =i/20;
                pt[i].y = (int) ((sample)*1.5);
                MoveToEx (hDC,pt[i].x,pt[i].y,NULL);
                while (i<num && sample!=(int)0xefffffff)
                {
                    // scale the sample

                    pt[i].x = i/20;
                    pt[i].y = (int) ((sample)*1.5);

                    LineTo(hDC, pt[i].x,pt[i].y);
                    i++;
                    sample= readSample(i, TRUE);

                }


            }
            DeleteObject(hPen);
            DeleteDC(hDC);
            
			EndPaint(hwnd, &ps);

        }
        return 0;

    case MM_WIM_OPEN:
        // Shrink down the save buffer

        pSaveBuffer = reinterpret_cast <PBYTE>(realloc (pSaveBuffer, 1)) ;




        // Add the buffers

        waveInAddBuffer (hWaveIn, pWaveHdr1, sizeof (WAVEHDR)) ;
        waveInAddBuffer (hWaveIn, pWaveHdr2, sizeof (WAVEHDR)) ;

        // Begin sampling

        bRecording = TRUE ;
        bEnding = FALSE ;
        dwDataLength = 0 ;
        waveInStart (hWaveIn) ;
        return TRUE ;




    case MM_WIM_DATA:

        // Reallocate save buffer memory

        pNewBuffer = reinterpret_cast <PBYTE> (realloc (pSaveBuffer, dwDataLength +
                                               ((PWAVEHDR) lParam)->dwBytesRecorded)) ;

        if (pNewBuffer == NULL)
        {
            waveInClose (hWaveIn) ;

            MessageBox (hwnd, szMemError, szAppName,
                        MB_ICONEXCLAMATION | MB_OK) ;
            return TRUE ;
        }

        pSaveBuffer = pNewBuffer ;
        CopyMemory (pSaveBuffer + dwDataLength, ((PWAVEHDR) lParam)->lpData,
                    ((PWAVEHDR) lParam)->dwBytesRecorded) ;

        dwDataLength += ((PWAVEHDR) lParam)->dwBytesRecorded ;

        if (bEnding)
        {
            waveInClose (hWaveIn) ;
            return TRUE ;
        }

        // Send out a new buffer

        waveInAddBuffer (hWaveIn, (PWAVEHDR) lParam, sizeof (WAVEHDR)) ;
        return TRUE ;

    case MM_WIM_CLOSE:
        // Free the buffer memory

        waveInUnprepareHeader (hWaveIn, pWaveHdr1, sizeof (WAVEHDR)) ;
        waveInUnprepareHeader (hWaveIn, pWaveHdr2, sizeof (WAVEHDR)) ;

        free (pBuffer1) ;
        free (pBuffer2) ;

        // Enable and disable buttons
        if (dwDataLength > 0)
        {
            EnableWindow (PlyButton,   TRUE)  ;
        }
        bRecording = FALSE ;

        if (bTerminating)
            SendMessage (hwnd, WM_SYSCOMMAND, SC_CLOSE, 0L) ;

        return TRUE ;

    case MM_WOM_OPEN:

        // Set up header

        pWaveHdr1->lpData          = reinterpret_cast <CHAR*>(pSaveBuffer) ;
        pWaveHdr1->dwBufferLength  = dwDataLength ;
        pWaveHdr1->dwBytesRecorded = 0 ;
        pWaveHdr1->dwUser          = 0 ;
        pWaveHdr1->dwFlags         = WHDR_BEGINLOOP | WHDR_ENDLOOP ;
        pWaveHdr1->dwLoops         = dwRepetitions ;
        pWaveHdr1->lpNext          = NULL ;
        pWaveHdr1->reserved        = 0 ;

        // Prepare and write

        waveOutPrepareHeader (hWaveOut, pWaveHdr1, sizeof (WAVEHDR)) ;
        waveOutWrite (hWaveOut, pWaveHdr1, sizeof (WAVEHDR)) ;

        bEnding = FALSE ;
        bPlaying = TRUE ;
        return TRUE ;

    case MM_WOM_DONE:

        waveOutUnprepareHeader (hWaveOut, pWaveHdr1, sizeof (WAVEHDR)) ;
        waveOutClose (hWaveOut) ;
        EnableWindow (PlyButton, TRUE);
        return TRUE ;

    case MM_WOM_CLOSE:

        dwRepetitions = 1 ;
        bPlaying = FALSE ;

        return TRUE ;





    case WM_COMMAND:

        switch (wParam)
        {


        case APP_SAVE:
        {

            char szFileName[MAX_PATH] = "";
            OPENFILENAME ofn;
            ZeroMemory(&ofn, sizeof(ofn));

            ofn.lStructSize= sizeof(ofn);
            ofn.hwndOwner = hwnd;
            ofn.lpstrFilter = "Wave Files(*.wav)\0*.wav\0";
            ofn.lpstrFile = szFileName;
            ofn.nMaxFile = MAX_PATH;
            ofn.Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT;
            ofn.lpstrDefExt = "wav";
            if (GetSaveFileName(&ofn))
            {
                if (szFileName)
                {
                    SaveWavFile(szFileName,pWaveHdr1);
                }
            }
        }
        break ;

        case APP_EXIT:
        {
            PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
            //cleanup before closing
            _fcloseall();
            fSuccess= DeleteFile(TEXT("temp.wav"));
        }
        break ;

        case IDC_RECORD:
        {

            EnableWindow (RecButton, FALSE) ;
            EnableWindow (PlyButton, FALSE) ;
            EnableWindow (StpButton, TRUE)  ;
            waveOutReset (hWaveOut) ;
            waveInReset (hWaveIn) ;
            pBuffer1=reinterpret_cast <PBYTE> (malloc(INP_BUFFER_SIZE) );
            pBuffer2= reinterpret_cast <PBYTE> ( malloc(INP_BUFFER_SIZE) );

            if (!pBuffer1 || !pBuffer2)
            {
                if (pBuffer1) free (pBuffer1) ;
                if (pBuffer2) free (pBuffer2) ;
                MessageBox (hwnd, szMemError, szAppName,
                            MB_ICONEXCLAMATION | MB_OK) ;
                return TRUE ;
            }
            // Open waveform audio for input



			SYSTEMTIME stime;
			FILETIME ltime;
			FILETIME ftTimeStamp;
			GetSystemTimeAsFileTime(&ftTimeStamp); //Gets the current system time
			FileTimeToLocalFileTime (&ftTimeStamp,&ltime);//convert in local time and store in ltime
			FileTimeToSystemTime(&ltime,&stime);//convert in system time and store in stim
			long tmstmp = stime.wMilliseconds + (stime.wSecond * 1000) + (stime.wMinute * 60000) + (stime.wHour * 3600 * 1000 );

			m_filestream << tmstmp;
			m_filestream << "\t";
			
			
			waveform.wFormatTag      = WAVE_FORMAT_PCM ;
            waveform.nChannels       = 1 ;
            waveform.nSamplesPerSec  = 11025 ;
            waveform.nAvgBytesPerSec = 11025 ;
            waveform.nBlockAlign     = 1 ;
            waveform.wBitsPerSample  = 8 ;
            waveform.cbSize          = 0 ;

            if (waveInOpen (&hWaveIn, WAVE_MAPPER, &waveform,
                            (DWORD) hwnd, 0, CALLBACK_WINDOW))
            {
                free (pBuffer1) ;
                free (pBuffer2) ;
            }
            // Set up headers and prepare them


            pWaveHdr1->lpData          =reinterpret_cast <CHAR*>( pBuffer1 ) ;
	

			m_filestream << "\n";

            pWaveHdr1->dwBufferLength  = INP_BUFFER_SIZE ;
            pWaveHdr1->dwBytesRecorded = 0 ;
            pWaveHdr1->dwUser          = 0 ;
            pWaveHdr1->dwFlags         = 0 ;
            pWaveHdr1->dwLoops         = 1 ;
            pWaveHdr1->lpNext          = NULL ;
            pWaveHdr1->reserved        = 0 ;

            waveInPrepareHeader (hWaveIn, pWaveHdr1, sizeof (WAVEHDR)) ;

            pWaveHdr2->lpData          = reinterpret_cast <CHAR*>(pBuffer2 ) ;
            pWaveHdr2->dwBufferLength  = INP_BUFFER_SIZE ;
            pWaveHdr2->dwBytesRecorded = 0 ;
            pWaveHdr2->dwUser          = 0 ;
            pWaveHdr2->dwFlags         = 0 ;
            pWaveHdr2->dwLoops         = 1 ;
            pWaveHdr2->lpNext          = NULL ;
            pWaveHdr2->reserved        = 0 ;

            waveInPrepareHeader (hWaveIn, pWaveHdr2, sizeof (WAVEHDR)) ;

        }
        break ;

        case IDC_STOP:
        {

            _fcloseall();
            EnableWindow (RecButton, TRUE) ;
            EnableWindow (StpButton, FALSE) ;
            EnableWindow (PlyButton, TRUE);
            bEnding = TRUE ;
            SaveWavFile("temp.wav",pWaveHdr1);

        }
        break ;

        case IDC_PLAY:
        {
            // play wav file
            bPlaying = TRUE;

            EnableWindow (PlyButton, FALSE);
            waveform.wFormatTag      = WAVE_FORMAT_PCM ;
            waveform.nChannels       = 1 ;
            waveform.nSamplesPerSec  = 11025 ;
            waveform.nAvgBytesPerSec = 11025 ;
            waveform.nBlockAlign     = 1 ;
            waveform.wBitsPerSample  = 8 ;
            waveform.cbSize          = 0 ;
            waveInReset (hWaveIn) ;
            waveOutReset (hWaveOut) ;
            if (waveOutOpen (&hWaveOut, WAVE_MAPPER, &waveform,
                             (DWORD) hwnd, 0, CALLBACK_WINDOW))
            {

                MessageBox (hwnd, szOpenError, szAppName,
                            MB_ICONEXCLAMATION | MB_OK) ;
            }





            Wav("temp.wav", hwnd);
           




            RECT rc;
            GetClientRect(hwnd, &rc);
            PLAY = TRUE;
            InvalidateRect(hwnd,&rc,TRUE);
        }
        break ;
        }
        break ;

    case WM_DESTROY:
        PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
        //cleanup before closing
        _fcloseall();
        fSuccess= DeleteFile(TEXT("temp.wav"));
        break;




    default:                      /* for messages that we don't deal with */
        return DefWindowProc (hwnd, message, wParam, lParam);
    }



    return 0;
}

//start of wave visualisation process

int readSample(int number,bool leftchannel)
{

    /*
      Reads sample number, returns it as an int, if
      this.mono==false we look at the leftchannel bool
      to determine which to return.

      number is in the range [0,length/byte_samp]

      returns 0xefffffff on failure
    */

    if (number>=0 && number<length/byte_samp)
    {
        // go to beginning of the file
        rewind(stream);

        // we start reading at sample_number * sample_size + header length
        int offset = number * 1 + 44;

        // unless this is a stereo file and the rightchannel is requested.
        if (!mono && !leftchannel)
        {
        offset += byte_samp/2;
        }

        // read this many bytes;
        int amount;
        amount=byte_samp;

        fseek(stream,offset,SEEK_CUR);
        short sample = 0;
        fread((void *)&sample,1,amount,stream);

        return sample;
    }
    else
    {
        // return 0xefffffff if failed
        return (int)0xefffffff;
    }
}
// Read the temporary wav file
void Wav(char *c, HWND hWnd)
{

    filename = new char[strlen(c)+1];
    strcpy_s(filename,strlen(c)+1,c);
    // open filepointer readonly
    wavfile = fopen_s(&stream,filename,"r");
    if (stream==NULL)
    {
        MessageBox(hWnd, "Could not open " + (char)filename,"Error", MB_OK);

    }
    else
    {
        // declare a char buff to store some values in
        char *buff = new char[5];
        buff[4]='\0';
        // read the first 4 bytes
        fread((void *)buff,1,4,stream);
        // the first four bytes should be 'RIFF'
        if (strcmp((char *)buff,"RIFF")==0)
        {

            // read byte 8,9,10 and 11
            fseek(stream,4,SEEK_CUR);
            fread((void *)buff,1,4,stream);
            // this should read "WAVE"
            if (strcmp((char *)buff,"WAVE")==0)
            {
                // read byte 12,13,14,15
                fread((void *)buff,1,4,stream);
                // this should read "fmt "
                if (strcmp((char *)buff,"fmt ")==0)
                {
                    fseek(stream,20,SEEK_CUR);
                    // final one read byte 36,37,38,39
                    fread((void *)buff,1,4,stream);
                    if (strcmp((char *)buff,"data")==0)
                    {


                        // Now we know it is a wav file, rewind the stream
                        rewind(stream);
                        // now is it mono or stereo ?
                        fseek(stream,22,SEEK_CUR);
                        fread((void *)buff,1,2,stream);
                        if (buff[0]==0x02)
                        {
                            mono=false;
                        }
                        else
                        {
                            mono=true;
                        }
                        // read the sample rate
                        fread((void *)&s_rate,1,4,stream);
                        fread((void *)&byte_sec,1,4,stream);
                        byte_samp=0;
                        fread((void *)&byte_samp,1,2,stream);
                        bit_samp=0;
                        fread((void *)&bit_samp,1,2,stream);
                        fseek(stream,4,SEEK_CUR);
                        fread((void *)&length,1,4,stream);
                    }
                }
            }
        }
        delete buff;

    }
}

void SaveWavFile(char *FileName, PWAVEHDR WaveHeader)
{

    fstream myFile (FileName, fstream::out | fstream::binary);

    int chunksize,pcmsize,NumSamples,subchunk1size;
    int audioFormat = 1;
    int numChannels = 1;
    int bitsPerSample = 8;



    NumSamples = ((long) (NUMPTS/sampleRate) * 1000);
    pcmsize = sizeof(PCMWAVEFORMAT);


    subchunk1size= 16;
    int byteRate = sampleRate*numChannels*bitsPerSample/8;
    int blockAlign = numChannels*bitsPerSample/8;
    int subchunk2size = WaveHeader->dwBufferLength*numChannels;
    chunksize = (36 + subchunk2size);
    // write the wav file per the wav file format
    myFile.seekp (0, ios::beg);
    myFile.write ("RIFF", 4);					// chunk id
    myFile.write ((char*) &chunksize, 4);	        	// chunk size (36 + SubChunk2Size))
    myFile.write ("WAVE", 4);					// format
    myFile.write ("fmt ", 4);					// subchunk1ID
    myFile.write ((char*) &subchunk1size, 4);			// subchunk1size (16 for PCM)
    myFile.write ((char*) &audioFormat, 2);			// AudioFormat (1 for PCM)
    myFile.write ((char*) &numChannels, 2);			// NumChannels
    myFile.write ((char*) &sampleRate, 4);			// sample rate
    myFile.write ((char*) &byteRate, 4);			// byte rate (SampleRate * NumChannels * BitsPerSample/8)
    myFile.write ((char*) &blockAlign, 2);			// block align (NumChannels * BitsPerSample/8)
    myFile.write ((char*) &bitsPerSample, 2);			// bits per sample
    myFile.write ("data", 4);					// subchunk2ID
    myFile.write ((char*) &subchunk2size, 4);			// subchunk2size (NumSamples * NumChannels * BitsPerSample/8)
    myFile.write (WaveHeader->lpData,WaveHeader->dwBufferLength);	// data

	myFile.close();
}



Have you got any idea how to overcome that?

Thank you once more!!
Best regards,
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2