一个windows录音程序把录的实时上传

C++语言 码拜 9年前 (2016-06-10) 1149次浏览
思考的是用生产者消费者的思路来上传的,但是不行
#include <windows.h>
#include <stdio.h>
#include<fstream>
#include <mmsystem.h>
#include <process.h>
#include<cstring>
#pragma comment(lib, “winmm.lib”)

#define BUFFER_SIZE (8000*16*1/8*5)    // 录制声音长度
#define FRAGMENT_SIZE 1024              // 缓存区大小
#define FRAGMENT_NUM 4                  // 缓存区个数

static unsigned char buffer[BUFFER_SIZE] = {0};
char buffermin[FRAGMENT_SIZE] = {0};
static int buf_count = 0;
const int END_PRODUCE_NUMBER = 8;  //生产产品个数
const int BUFFER_NUMBER = 4;          //缓冲区个数
char* g_Buffer[BUFFER_NUMBER];          //缓冲池
int g_i;
int g_j;
//信号量与关键段
CRITICAL_SECTION g_cs;
HANDLE g_hSemaphoreBufferEmpty, g_hSemaphoreBufferFull;
void CALLBACK waveInProc(HWAVEIN hwi,
UINT uMsg,
DWORD_PTR dwInstance,
DWORD_PTR dwParam1,
DWORD_PTR dwParam2     );
void CALLBACK waveOutProc(  HWAVEOUT hwo,
UINT uMsg,
DWORD_PTR dwInstance,
DWORD_PTR dwParam1,
DWORD_PTR dwParam2     );

// 入口
//生产者线程函数
unsigned int __stdcall ProducerThreadFun(PVOID pM)
{
UINT uMsg;
while(WIM_DATA==uMsg)
{
//等待有空的缓冲区出现
WaitForSingleObject(g_hSemaphoreBufferEmpty, INFINITE);

//互斥的访问缓冲区
EnterCriticalSection(&g_cs);
memcpy(g_Buffer[g_i],buffermin , FRAGMENT_SIZE);
//g_Buffer[g_i] = buffermin;
printf(“生产者在缓冲池第%d个缓冲区中投放数据%d\n”, g_i, g_Buffer[g_i]);
g_i = (g_i + 1) % BUFFER_NUMBER;
LeaveCriticalSection(&g_cs);

//通知消费者有新数据了
ReleaseSemaphore(g_hSemaphoreBufferFull, 1, NULL);
}
printf(“生产者完成任务,线程结束运行\n”);
return 0;
}
//消费者线程函数
unsigned int __stdcall ConsumerThreadFun(PVOID pM)
{
while (true)
{
//等待非空的缓冲区出现
WaitForSingleObject(g_hSemaphoreBufferFull, INFINITE);

//互斥的访问缓冲区
EnterCriticalSection(&g_cs);
int temp = BUFFER_SIZE – buf_count;

memcpy(buffer+buf_count,g_Buffer[g_j] ,FRAGMENT_SIZE);

buf_count += temp;
printf(”  编号为%d的消费者从缓冲池中第%d个缓冲区取出数据%d\n”, GetCurrentThreadId(), g_j, g_Buffer[g_j]);

g_j = (g_j + 1) % BUFFER_SIZE;
LeaveCriticalSection(&g_cs);

Sleep(50); //some other work to do

ReleaseSemaphore(g_hSemaphoreBufferEmpty, 1, NULL);
}

printf(”  编号为%d的消费者收到通知,线程结束运行\n”, GetCurrentThreadId());

return 0;
}
int main()
{
InitializeCriticalSection(&g_cs);
//初始化信号量,一个记录有产品的缓冲区个数,另一个记录空缓冲区个数.
g_hSemaphoreBufferEmpty = CreateSemaphore(NULL, 4, 4, NULL);
g_hSemaphoreBufferFull  = CreateSemaphore(NULL, 0, 4, NULL);
g_i = 0;
g_j = 0;
memset(g_Buffer, 0, sizeof(g_Buffer));

const int THREADNUM = 2;
HANDLE hThread[THREADNUM];
//生产者线程
hThread[0] = (HANDLE)_beginthreadex(NULL, 0, ProducerThreadFun, NULL,CREATE_SUSPEND, NULL);
//消费者线程
hThread[1] = (HANDLE)_beginthreadex(NULL, 0, ConsumerThreadFun, NULL, 0, NULL);

/* 录音 */

// Device
int nReturn = waveInGetNumDevs();
printf(“输入设备数目:%d\n”, nReturn);
for (int i=0; i<nReturn; i++)         //i是设备id
{
WAVEINCAPS wic;                   //一个指向WAVEINCAPS结构的指针
waveInGetDevCaps(i, &wic, sizeof(WAVEINCAPS));
printf(“#%d\t设备名:%s\n”, i, wic.szPname);   //szPname设备名称
}

// open
HWAVEIN hWaveIn;                         //设备句柄
WAVEFORMATEX wavform;                    //一个所需的格式进行录音的WAVEFORMATEX结构的指针
wavform.wFormatTag = WAVE_FORMAT_PCM;    //波形声音的格式,单声道双声道使用WAVE_FORMAT_PCM.
wavform.nChannels = 1;                   //声道数量
wavform.nSamplesPerSec = 8000;          //采样率.wFormatTag为WAVE_FORMAT_PCM时,有8.0kHz,11.025kHz,22.05kHz,和44.1kHz.
wavform.nAvgBytesPerSec = 8000*16*1/8;  //每秒的采样字节数.通过nSamplesPerSec * nChannels * wBitsPerSample / 8计算
wavform.nBlockAlign = 2;                 //每次采样的字节数.通过nChannels * wBitsPerSample / 8计算
wavform.wBitsPerSample = 16;             //采样位数.wFormatTag为WAVE_FORMAT_PCM时,为8或16
wavform.cbSize = 0;

waveInOpen(&hWaveIn, WAVE_MAPPER, &wavform, (DWORD_PTR)waveInProc, 0, CALLBACK_FUNCTION);  //指定一个需要打开的设备标识.可以使用WAVE_MAPPER选择一个按指定录音格式录音的设备;waveInProc回调处理参数;CALLBACK_FUNCTION是打开设备的一个通知信息

WAVEINCAPS wic;
waveInGetDevCaps((UINT_PTR)hWaveIn, &wic, sizeof(WAVEINCAPS));
printf(“打开的输入设备:%s\n”, wic.szPname);

// prepare buffer
static WAVEHDR wh[FRAGMENT_NUM];     //指向WAVEHDR结构的指针,标识准备的缓冲区
for (int i=0; i<FRAGMENT_NUM; i++)
{
wh[i].lpData = new char[FRAGMENT_SIZE];  //指向波形格式的缓冲区
wh[i].dwBufferLength = FRAGMENT_SIZE;
wh[i].dwBytesRecorded = 0;               //当前存储数据
wh[i].dwUser = NULL;
wh[i].dwFlags = 0;                       //为缓冲区提供的信息
wh[i].dwLoops = 1;                       //输出时使用,标识播放次数
wh[i].lpNext = NULL;
wh[i].reserved = 0;

waveInPrepareHeader(hWaveIn, &wh[i], sizeof(WAVEHDR));
waveInAddBuffer(hWaveIn, &wh[i], sizeof(WAVEHDR));
}

// record
printf(“Start to Record…\n”);

buf_count = 0;
waveInStart(hWaveIn);

while (buf_count < BUFFER_SIZE)
{
Sleep(1);
}

printf(“Record Over!\n\n”);

// clean
waveInStop(hWaveIn);
waveInReset(hWaveIn);
for (int i=0; i<FRAGMENT_NUM; i++)
{
waveInUnprepareHeader(hWaveIn, &wh[i], sizeof(WAVEHDR));
delete wh[i].lpData;
}
waveInClose(hWaveIn);

system(“pause”);
printf(“\n”);

/* 放音 */

// Device
nReturn = waveOutGetNumDevs();
printf(“\n放音输出设备数目:%d\n”, nReturn);
for (int i=0; i<nReturn; i++)
{
WAVEOUTCAPS woc;
waveOutGetDevCaps(i, &woc, sizeof(WAVEOUTCAPS));
printf(“#%d\t设备名:%s\n”, i, wic.szPname);
}

// open
HWAVEOUT hWaveOut;
waveOutOpen(&hWaveOut, WAVE_MAPPER, &wavform, (DWORD_PTR)waveOutProc, 0, CALLBACK_FUNCTION);

WAVEOUTCAPS woc;
waveOutGetDevCaps((UINT_PTR)hWaveOut, &woc, sizeof(WAVEOUTCAPS));
printf(“打开的输出设备:%s\n”, wic.szPname);

// prepare buffer
WAVEHDR wavhdr;
wavhdr.lpData = (LPSTR)buffer;
wavhdr.dwBufferLength = BUFFER_SIZE;
wavhdr.dwFlags = 0;
wavhdr.dwLoops = 0;

waveOutPrepareHeader(hWaveOut, &wavhdr, sizeof(WAVEHDR));

// play
printf(“Start to Play…\n”);

buf_count = 0;
waveOutWrite(hWaveOut, &wavhdr, sizeof(WAVEHDR));
while (buf_count < BUFFER_SIZE)
{
Sleep(1);
}

// clean
waveOutReset(hWaveOut);
waveOutUnprepareHeader(hWaveOut, &wavhdr, sizeof(WAVEHDR));
waveOutClose(hWaveOut);

printf(“Play Over!\n\n”);
FILE* fp = fopen(“D:\录音.wav”, “wb+”);
fseek(fp, 0, SEEK_SET);
fwrite(buffer,BUFFER_SIZE, 1, fp);
fclose(fp);
printf(“write success!\n\n”);
fclose(fp);
/*std::ofstream ofs;
ofs.open(“D:\录音.wav”);
for(int i = 0; i < BUFFER_SIZE; i ++)
ofs <<buffer[i];
ofs.close();*/
system(“pause”);

return 0;
WaitForMultipleObjects(THREADNUM, hThread, TRUE, INFINITE);
for (int i = 0; i < THREADNUM; i++)
CloseHandle(hThread[i]);

//销毁信号量和关键段
CloseHandle(g_hSemaphoreBufferEmpty);
CloseHandle(g_hSemaphoreBufferFull);
DeleteCriticalSection(&g_cs);
return 0;
}
// 录音回调函数
void CALLBACK waveInProc(HWAVEIN hwi,
UINT uMsg,
DWORD_PTR dwInstance,
DWORD_PTR dwParam1,
DWORD_PTR dwParam2     )
{
LPWAVEHDR pwh = (LPWAVEHDR)dwParam1;

if ((WIM_DATA==uMsg) && (buf_count<BUFFER_SIZE))
{
int temp = BUFFER_SIZE – buf_count;
temp = (temp>pwh->dwBytesRecorded) ? pwh->dwBytesRecorded : temp;
memcpy(buffer+buf_count, pwh->lpData, temp);
memcpy(buffermin, pwh->lpData, temp);
buf_count += temp;
// ResumeThread( hThread[0]);
waveInAddBuffer(hwi, pwh, sizeof(WAVEHDR));
}
}

// 放音回调函数
void CALLBACK waveOutProc(  HWAVEOUT hwo,
UINT uMsg,
DWORD_PTR dwInstance,
DWORD_PTR dwParam1,
DWORD_PTR dwParam2     )
{
if (WOM_DONE == uMsg)
{
buf_count = BUFFER_SIZE;
}
}
首先不能把进程挂起,把那个改成0也出错,不知道怎么回事了

解决方案

100

仅供参考:

//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#ifdef _MSC_VER
    #pragma warning(disable:4996)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
    #include <windows.h>
    #include <process.h>
    #include <io.h>
    #define  MYVOID             void
    #define  vsnprintf          _vsnprintf
#else
    #include <unistd.h>
    #include <sys/time.h>
    #include <pthread.h>
    #define  CRITICAL_SECTION   pthread_mutex_t
    #define  MYVOID             void *
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef _MSC_VER
void Lock(CRITICAL_SECTION *l) {
    EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
    LeaveCriticalSection(l);
}
void sleep_ms(int ms) {
    Sleep(ms);
}
#else
void Lock(CRITICAL_SECTION *l) {
    pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
    pthread_mutex_unlock(l);
}
void sleep_ms(int ms) {
    usleep(ms*1000);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
    struct tm *now;
    struct timeb tb;
    if (NULL==pszFmt||0==pszFmt[0]) return;
    vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename1,"a");
    if (NULL!=flog) {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE) {
            fclose(flog);
            if (rename(logfilename1,logfilename2)) {
                remove(logfilename2);
                rename(logfilename1,logfilename2);
            }
        } else {
            fclose(flog);
        }
    }
}
void Log(const char *pszFmt,...) {
    va_list argp;
    Lock(&cs_log);
    va_start(argp,pszFmt);
    LogV(pszFmt,argp);
    va_end(argp);
    Unlock(&cs_log);
}
//Log}
#define ASIZE    200
#define BSIZE    240
#define CSIZE      2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX ;
CRITICAL_SECTION cs_BBB ;
struct FIFO_BUFFER {
    int  head;
    int  tail;
    int  size;
    char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
    int i,j,k;
    char binstr[80];
    Lock(&cs_HEX);
    for (i=0;i<len;i++) {
        if (0==(i%16)) {
            sprintf(binstr,"%03d %04x -",cn,i);
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        } else if (15==(i%16)) {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
            sprintf(binstr,"%s  ",binstr);
            for (j=i-15;j<=i;j++) {
                sprintf(binstr,"%s%c",binstr,("!"<buf[j]&&buf[j]<="~")?buf[j]:".");
            }
            Log("%s\n",binstr);
        } else {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        }
    }
    if (0!=(i%16)) {
        k=16-(i%16);
        for (j=0;j<k;j++) {
            sprintf(binstr,"%s   ",binstr);
        }
        sprintf(binstr,"%s  ",binstr);
        k=16-k;
        for (j=i-k;j<i;j++) {
            sprintf(binstr,"%s%c",binstr,("!"<buf[j]&&buf[j]<="~")?buf[j]:".");
        }
        Log("%s\n",binstr);
    }
    Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;
    lent=0;
    Lock(cs);
    if (fbuf->size>=len) {
        lent=len;
        if (fbuf->head+lent>BSIZE) {
            len1=BSIZE-fbuf->head;
            memcpy(buf     ,fbuf->data+fbuf->head,len1);
            len2=lent-len1;
            memcpy(buf+len1,fbuf->data           ,len2);
            fbuf->head=len2;
        } else {
            memcpy(buf     ,fbuf->data+fbuf->head,lent);
            fbuf->head+=lent;
        }
        fbuf->size-=lent;
    }
    Unlock(cs);
    return lent;
}
MYVOID thdB(void *pcn) {
    char        *recv_buf;
    int          recv_nbytes;
    int          cn;
    int          wc;
    int          pb;
    cn=(int)pcn;
    Log("%03d thdB              thread begin...\n",cn);
    while (1) {
        sleep_ms(10);
        recv_buf=(char *)Cbuf;
        recv_nbytes=CSIZE;
        wc=0;
        while (1) {
            pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
            if (pb) {
                Log("%03d recv %d bytes\n",cn,pb);
                HexDump(cn,recv_buf,pb);
                sleep_ms(1);
            } else {
                sleep_ms(1000);
            }
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef _MSC_VER
    pthread_exit(NULL);
#endif
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;
    Lock(cs);
    lent=len;
    if (fbuf->size+lent>BSIZE) {
        lent=BSIZE-fbuf->size;
    }
    if (fbuf->tail+lent>BSIZE) {
        len1=BSIZE-fbuf->tail;
        memcpy(fbuf->data+fbuf->tail,buf     ,len1);
        len2=lent-len1;
        memcpy(fbuf->data           ,buf+len1,len2);
        fbuf->tail=len2;
    } else {
        memcpy(fbuf->data+fbuf->tail,buf     ,lent);
        fbuf->tail+=lent;
    }
    fbuf->size+=lent;
    Unlock(cs);
    return lent;
}
MYVOID thdA(void *pcn) {
    char        *send_buf;
    int          send_nbytes;
    int          cn;
    int          wc;
    int           a;
    int          pa;
    cn=(int)pcn;
    Log("%03d thdA              thread begin...\n",cn);
    a=0;
    while (1) {
        sleep_ms(100);
        memset(Abuf,a,ASIZE);
        a=(a+1)%256;
        if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
        send_buf=(char *)Abuf;
        send_nbytes=ASIZE;
        Log("%03d sending %d bytes\n",cn,send_nbytes);
        HexDump(cn,send_buf,send_nbytes);
        wc=0;
        while (1) {
            pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
            Log("%03d sent %d bytes\n",cn,pa);
            HexDump(cn,send_buf,pa);
            send_buf+=pa;
            send_nbytes-=pa;
            if (send_nbytes<=0) break;//
            sleep_ms(1000);
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef _MSC_VER
    pthread_exit(NULL);
#endif
}
int main() {
#ifdef _MSC_VER
    InitializeCriticalSection(&cs_log);
    InitializeCriticalSection(&cs_HEX );
    InitializeCriticalSection(&cs_BBB );
#else
    pthread_t threads[2];
    int threadsN;
    int rc;
    pthread_mutex_init(&cs_log,NULL);
    pthread_mutex_init(&cs_HEX,NULL);
    pthread_mutex_init(&cs_BBB,NULL);
#endif
    Log("Start===========================================================\n");
    BBB.head=0;
    BBB.tail=0;
    BBB.size=0;
#ifdef _MSC_VER
    _beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
    _beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);
#else
    threadsN=0;
    rc=pthread_create(&(threads[threadsN++]),NULL,thdA,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
    rc=pthread_create(&(threads[threadsN++]),NULL,thdB,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
#endif
    if (!access("No_Loop",0)) {
        remove("No_Loop");
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    while (1) {
        sleep_ms(1000);
        if (No_Loop) break;//
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    sleep_ms(3000);
    Log("End=============================================================\n");
#ifdef _MSC_VER
    DeleteCriticalSection(&cs_BBB );
    DeleteCriticalSection(&cs_HEX );
    DeleteCriticalSection(&cs_log);
#else
    pthread_mutex_destroy(&cs_BBB);
    pthread_mutex_destroy(&cs_HEX);
    pthread_mutex_destroy(&cs_log);
#endif
    return 0;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明一个windows录音程序把录的实时上传
喜欢 (0)
[1034331897@qq.com]
分享 (0)