Samstag, 15. Oktober 2011

EE4209/EE5809 Digital Audio : Reading and Writing Wav Files Using C

EE4209/EE5809 Digital Audio : Reading and Writing Wav Files Using C
http://www.labbookpages.co.uk/audio/wavFiles.html#c

Reading WAV files

Audio signal are stored in Microsoft WAV file format, it is necessary to write program to read WAV file header to determine the signal parameters, such as sampling frequency, number of channels, bit per sample, and etc.

A reference C program is supplied in the Appendix for students to easily get start with reading WAV file. A C structure type for the WAV header information was defined in the program, i.e., WAVE.

To read the WAV header information from file is simply to read the data at the beginning of the file with the number of bytes specified by the size of header
structure. Once the header is read, the program should search for the data chunk and ignore other information which is irrelevant here.

A C subroutine Prepare_File() can be used for this purpose. Once the file read pointer is ready pointing at the data section of the data chunk, you can read block of 16-bit PCM samples into a buffer declared as short integer buffer in C to start
the process of encoder in a block by block fashion.

Note that if you are working on stereo audio, the left and right channels are coded independently, and the samples for the left and right channels are stored as interleave samples in WAV file.



// read WAV filer header and prepare file pointer for reading the data chunk

long Prepare_File(FILE *fpi, WAVE *header)
{
unsigned long filesize, totaldata ;
long sampling_rate ;
int stereo ;
char buf[5] ;
int freq ;
int i, n ;

read(fpi->fd, header, sizeof(WAVE)) ;
if(strncmp(header->wavefmt, "WAVEfmt ", 8))
{
printf("Format Error!\n") ;
fcloseall() ;
return(-1) ;
}

stereo = header->mode-1;
freq = header->sampling_rate ;
if(strncmp(header->data, "data", 4))
{
buf[4] = 0 ;
rewind(fpi) ;
read(fpi->fd, buf, 4*sizeof(char)) ;
n = sizeof(WAVE) ;
while(strncmp(buf, "data", 4))
{
for(i=0; i<3; i++)
buf[i] = buf[i+1] ;
read(fpi->fd, &buf[3], sizeof(char)) ;
n += 1 ;
}
read(fpi->fd, &(header->num_data), sizeof(long)) ;
}
filesize = header->num_data ;
totaldata=filesize>>2;
return(totaldata) ;
}

------- - - - -

int readdata(FILE *fp, short int ibuf[], int n)
{
int m ;

m = read(fp->fd, ibuf, n*sizeof(short int)) ;
if(m == -1)
return(-1) ;
m = m / sizeof(short int) ;

return(m) ;
}



1 Kommentar:

Anonym hat gesagt…

自己人?