scratch/output/Scratch/en/blog/2010-10-14-Fun-with-wav/code/wavsum.c

60 lines
1.5 KiB
C
Raw Normal View History

2010-10-14 13:30:15 +00:00
#include <stdio.h>
#include <stdlib.h>
2010-10-26 14:49:21 +00:00
#include <stdint.h>
2010-10-14 13:30:15 +00:00
struct wavfile
{
2010-10-26 14:49:21 +00:00
char id[4]; // should always contain "RIFF"
int totallength; // total file length minus 8
char wavefmt[8]; // should be "WAVEfmt "
int format; // 16 for PCM format
short pcm; // 1 for PCM format
short channels; // channels
int frequency; // sampling frequency
int bytes_per_second;
short bytes_by_capture;
short bits_per_sample;
char data[4]; // should always contain "data"
int bytes_in_data;
};
2010-10-14 13:30:15 +00:00
int main(int argc, char *argv[]) {
char *filename=argv[1];
FILE *wav = fopen(filename,"rb");
struct wavfile header;
if ( wav == NULL ) {
2010-10-26 14:49:21 +00:00
fprintf(stderr,"Can't open input file %s", filename);
2010-10-14 13:30:15 +00:00
exit(1);
}
// read header
2010-10-26 14:49:21 +00:00
if ( fread(&header,sizeof(header),1,wav) < 1 )
{
fprintf(stderr,"Can't read file header\n");
2010-10-14 13:30:15 +00:00
exit(1);
}
2010-10-26 14:49:21 +00:00
if ( header.id[0] != 'R'
|| header.id[1] != 'I'
|| header.id[2] != 'F'
|| header.id[3] != 'F' ) {
2010-10-14 13:30:15 +00:00
fprintf(stderr,"ERROR: Not wav format\n");
exit(1);
}
fprintf(stderr,"wav format\n");
// read data
2010-10-26 14:49:21 +00:00
long sum=0;
short value=0;
2010-10-14 13:30:15 +00:00
while( fread(&value,sizeof(value),1,wav) ) {
2010-10-26 14:49:21 +00:00
// fprintf(stderr,"%d\n", value);
2010-10-14 13:30:15 +00:00
if (value<0) { value=-value; }
sum += value;
}
2010-10-26 14:49:21 +00:00
printf("%ld\n",sum);
2010-10-14 13:30:15 +00:00
exit(0);
}