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-14 14:30:48 +00:00
#include <stdint.h>
2010-10-14 13:30:15 +00:00
struct wavfile
{
2010-10-14 22:33:07 +00:00
char id[4]; // should always contain "RIFF"
2010-10-14 14:23:07 +00:00
int32_t totallength; // total file length minus 8
2010-10-14 22:33:07 +00:00
char wavefmt[8]; // should be "WAVEfmt "
2010-10-14 14:23:07 +00:00
int32_t format; // 16 for PCM format
2010-10-14 22:33:07 +00:00
int16_t pcm; // 1 for PCM format
int16_t channels; // channels
2010-10-14 14:23:07 +00:00
int32_t frequency; // sampling frequency
int32_t bytes_per_second;
2010-10-14 22:33:07 +00:00
int16_t bytes_by_capture;
int16_t bits_per_sample;
char data[4]; // should always contain "data"
2010-10-14 14:23:07 +00:00
int32_t 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 ) {
fprintf(stderr,"Can't open input file %s", filename);
exit(1);
}
// read header
2010-10-14 22:26:39 +00:00
if ( fread(&header,sizeof(header),1,wav) < 1 )
2010-10-14 13:30:15 +00:00
{
fprintf(stderr,"Can't read file header\n");
exit(1);
}
if ( header.id[0] != 'R'
|| header.id[1] != 'I'
|| header.id[2] != 'F'
|| header.id[3] != 'F' ) {
fprintf(stderr,"ERROR: Not wav format\n");
exit(1);
}
fprintf(stderr,"wav format\n");
// read data
long sum=0;
2010-10-14 14:23:07 +00:00
int16_t value=0;
2010-10-14 13:30:15 +00:00
while( fread(&value,sizeof(value),1,wav) ) {
// fprintf(stderr,"%d\n", value);
if (value<0) { value=-value; }
sum += value;
}
printf("%ld\n",sum);
exit(0);
}