Playback audio data from memory in Windows

Source: Internet
Author: User


Continue previous Article:understand Wave format, and implement a wave reader, in here, I'll demonstrate how to play Audio in Windows.

(Zeroth is wave format, you could refer to previous article.)

First, the struct WaveFormatEx would is used, the members of WaveFormatEx is very explicit, I do not explain that.


Second, the structure WAVEHDR, which is for managing audio buffer. One should set audio buffer in the WAVEHDR structure to require Windows to play this audio.


The functions would be used:

Waveoutopen: Open the audio output device for playback.
The function needs a hwaveout as output.
One should has the set WAVEHDR to feed the waveoutopen.
The function needs to set a callback function, Waveoutproc.

Waveoutprepareheader/waveoutprepareheader:
Set the The structure WAVEHDR be prepared/cleaned.

Waveoutwrite:set the audio data to the audio output device.


To ensure the audio playback be smooth, it's necessary to use 2 block of buffer:
One for preparing, one for playing, and Interleave form (very similar to producer consumer semaphores problem). Here, I use Entercriticalsection/leavecriticalsection.



My code is below, the full code with Previouse is too long, I omit the previous code:
The part should is inserted after the line


#define Max_str_len       256


#define KB (1024x768)#define SEND_SIZE (8*KB)#define BLOCK_SIZE (16*KB)#define BLOCK_COUNT (2)#include <windows.h>#include <Mmreg.h>Critical_section wavecriticalsection; WaveFormatEx wfmt;/*for Debug, or the should not be global variable*/voidCALLBACKWaveoutproc(Hwaveout device, UINT umsg, DWORD dwinstance, DWORD dwParam1, DWORD dwParam2) {Static unsigned intCnt= 0; DWORD*Pfreeblockcounter; Pfreeblockcounter=(DWORD*)(Long Long) Dwinstance;Switch(umsg) { Casewom_done:printf ("Playing time =%1.3f s\ n"Cnt*Block_size/(float) (wfmt.navgbytespersec)); Cnt++; EnterCriticalSection (&Wavecriticalsection); (*Pfreeblockcounter)++; LeaveCriticalSection (&Wavecriticalsection); Break; CaseWom_open:initializecriticalsection (&Wavecriticalsection); Break; CaseWom_close:deletecriticalsection (&Wavecriticalsection); Break; }/*if umsg = = wom_done*/}/*wavecallback*/ 



Below code should is insert in front of the ' return ' line in main:


 Char *Paudiodata; Paudiodata=(Char*) malloc (Audiodatalen); Fread (Paudiodata,1, Audiodatalen, Pwavefile); Fclose (Pwavefile);/*step 0, variables*/MMRESULT ret; Hwaveout Hdevice;intWavefreeblockcount; Wavehdr*Pwaveheaderwithblock;intWavecurrentblock;/*step 1:initialize * /Hdevice= NULL;/*set waveformatex*/Wfmt.wformattag=(WORD) WAVE_FORMAT_PCM; Wfmt.nsamplespersec=(WORD) nsamplespersec; Wfmt.wbitspersample=(WORD) BitsPerSample; Wfmt.nchannels=(WORD) Nchannel; Wfmt.nblockalign=(WORD) (Wfmt.nchannels*(BitsPerSample/8)); Wfmt.navgbytespersec=Wfmt.nsamplespersec*Wfmt.nblockalign; Wfmt.cbsize= 0;/*set up callback function to play audio*/Ret=Waveoutopen (&Hdevice, Wave_mapper,&WFMT, (Dword_ptr) Waveoutproc, (DWORD_PTR)&Wavefreeblockcount, callback_function);if(0 !=RET) {CharErrstr[max_str_len]; Waveoutgeterrortext (ret,&errstr[0], Max_str_len); printf"error =%s\ n",&errstr[0]);GotoFlag_end_main; }/*if * *    /** Prepare and set up buffer for struct WAVEHDRUse 2 buffer to load audio data in interleave form */Pwaveheaderwithblock=(WAVEHDR*) HeapAlloc (GetProcessHeap (), Heap_zero_memory, (block_size+ sizeof(WAVEHDR))*Block_count);if(NULL ==Pwaveheaderwithblock)GotoFlag_end_main; Wavehdr*Pblockheader; Pblockheader=(WAVEHDR*) Pwaveheaderwithblock; for(intI= 0; I<Block_count; I++) {Pblockheader[i].dwbufferlength=Block_size; Pblockheader[i].lpdata=(LPSTR) (Pwaveheaderwithblock)+ sizeof(WAVEHDR)*Block_count+I*Block_size; }/*for i*/Wavefreeblockcount=Block_count; Wavecurrentblock= 0;if(NULL ==Pwaveheaderwithblock)GotoFlag_end_main;unsigned intRemainderlen; Remainderlen=Audiodatalen;Char *Pmovaudiodata; Pmovaudiodata=Paudiodata; Pmovaudiodata+=(unsigned int) (nsamplespersec*Nchannel*2); Remainderlen-=(unsigned int) (nsamplespersec*Nchannel*2);unsigned intCnt Cnt= 0; while(Remainderlen>Send_size) {printf ("Send time =%1.3f s\ n"Cnt*Send_size/((float) (bytespersec)); Cnt++;/** Step 3 play audio!  */Wavehdr*Pcurrentwaveheader;unsigned Longremain;unsigned intSizeChar *PData; Size=Send_size; Pcurrentwaveheader= &Pwaveheaderwithblock[wavecurrentblock]; PData=(Char*) Pmovaudiodata; while(Size> 0)   {/*Make sure the header we ' re going to use is unpreparedcleans up the preparation   */     if(whdr_prepared&Pcurrentwaveheader -DwFlags) Waveoutunprepareheader (Hdevice, Pcurrentwaveheader,sizeof(WAVEHDR));if(Size<(int) (Block_size-Pcurrentwaveheader -Dwuser)) {/*the buffer is enough, stow all data in current WAVEHDR's buffer.    */memcpy (Pcurrentwaveheader -Lpdata+Pcurrentwaveheader -Dwuser, pData, size); Pcurrentwaveheader -Dwuser+=Size Break; }/*if*/   /*the Buffer would is full */Remain=Block_size-(unsigned Long) Pcurrentwaveheader -Dwuser; memcpy (Pcurrentwaveheader -Lpdata+Pcurrentwaveheader -Dwuser, PData, remain);/*remaining would is stowed in the other WAVEHDR, note the size here * /Size-=remain; PData+=remain;/*full size of the WAVEHDR ' s buffer is block_size * /Pcurrentwaveheader -Dwbufferlength=Block_size;/*preparation...*/Waveoutprepareheader (Hdevice, Pcurrentwaveheader,sizeof(WAVEHDR));/*write The data to audio device * /Waveoutwrite (Hdevice, Pcurrentwaveheader,sizeof(WAVEHDR));/*The data or previous data is under playingassure the counter wavefreeblockcount would not be disorder   */EnterCriticalSection (&Wavecriticalsection); Wavefreeblockcount--; LeaveCriticalSection (&Wavecriticalsection);/** Wait for there are block in free   */    while(0 ==Wavefreeblockcount) Sleep (5);/** Point to the next block   */Wavecurrentblock++; Wavecurrentblock%=Block_count; Pcurrentwaveheader= &Pwaveheaderwithblock[wavecurrentblock]; Pcurrentwaveheader -Dwuser= 0; }/*while*/Pmovaudiodata+=Send_size; Remainderlen-=Send_size; }/*while remainderlen > send_size*/ //sendaudiobuf (Pmovaudiodata, Remainderlen);Flag_end_main:  for(intI= 0; I<Wavefreeblockcount; I++){if(NULL !=Pwaveheaderwithblock) {if(Pwaveheaderwithblock[i].dwflags&whdr_prepared) Waveoutunprepareheader (Hdevice,&Pwaveheaderwithblock[i],sizeof(WAVEHDR)); }/*if*/Pwaveheaderwithblock= NULL; }/*for I wavefreeblockcount*/ if(NULL !=Hdevice) Waveoutclose (hdevice); Hdevice= NULL;if(NULL !=Pwaveheaderwithblock) HeapFree (GetProcessHeap (),0, Pwaveheaderwithblock); Pwaveheaderwithblock= NULL;



Now there is a Hand-made wave player in Windows.

Playback audio data from memory in Windows

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.