/* A simple sound library for CSE 20211 by Douglas Thain For course assignments, you should not change this file. For complete documentation, see: http://www.nd.edu/~dthain/courses/cse20211/fall2013/wavfile */ #include "wavfile.h" #include #include #include #ifdef __cplusplus extern "C" { #endif FILE* wavfile_write_open(const char* filename) { struct wavfile_header header; int samples_per_second = WAVFILE_SAMPLES_PER_SECOND; int bits_per_sample = 16; strncpy(header.riff_tag, "RIFF", 4); strncpy(header.wave_tag, "WAVE", 4); strncpy(header.fmt_tag, "fmt ", 4); strncpy(header.data_tag, "data", 4); header.riff_length = 0; header.fmt_length = 16; header.audio_format = 1; header.num_channels = 1; header.sample_rate = samples_per_second; header.byte_rate = samples_per_second * (bits_per_sample / 8); header.block_align = bits_per_sample / 8; header.bits_per_sample = bits_per_sample; header.data_length = 0; FILE* file = fopen(filename, "w+"); if (!file) return 0; fwrite(&header, sizeof(header), 1, file); fflush(file); return file; } FILE* wavfile_read_open(const char* filename, struct wavfile_header* header) { FILE* file = 0; if (header != NULL) { file = fopen(filename, "rb"); if (!file) return 0; int r = fread(header, sizeof(struct wavfile_header), 1, file); r = sizeof(struct wavfile_header); printf("%d\n", r); } else { return 0; } return file; } long wavfile_read(FILE* file, short data[], int length) { return fread(data, sizeof(short), length, file); } void wavfile_write(FILE* file, short data[], int length) { fwrite(data, sizeof(short), length, file); } void wavfile_write_close(FILE* file) { int file_length = ftell(file); int data_length = file_length - sizeof(struct wavfile_header); fseek(file, sizeof(struct wavfile_header) - sizeof(int), SEEK_SET); fwrite(&data_length, sizeof(data_length), 1, file); int riff_length = file_length - 8; fseek(file, 4, SEEK_SET); fwrite(&riff_length, sizeof(riff_length), 1, file); fflush(file); fclose(file); } /*read the data from specified postion and channel*/ static short wavfile_read_pos(FILE* file, int channel_num, int channel_index, int pos) { short value; long index = 44 + (pos * channel_num + channel_index) * sizeof(short); fseek(file, index, SEEK_SET); fread(&value, sizeof(short), 1, file); return value; } void wavfile_read_channel(FILE* file, short data[], int channel_num, int channel_index, int start_pos, int length) { int i; for (i = 0; i < length; ++i) { data[i] = wavfile_read_pos(file, channel_num, channel_index, start_pos + i); } } #ifdef __cplusplus } #endif