old-bannertool/source/pc/wav.cpp

69 lines
1.5 KiB
C++
Raw Normal View History

#include "wav.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
2015-01-26 03:04:27 +00:00
bool wav_find_chunk(FILE* fd, const char* magic) {
char curr[5] = {0};
while(strcmp(curr, magic) != 0) {
u32 read = (u32) fread(curr, 1, 4, fd);
if(read == 0) {
return false;
}
}
fseek(fd, -4, SEEK_CUR);
return true;
}
2015-01-26 03:04:27 +00:00
WAV* wav_read(const char* file) {
FILE* fd = fopen(file, "r");
if(!fd) {
printf("ERROR: Could not open WAV file: %s\n", strerror(errno));
return NULL;
}
2015-01-26 03:04:27 +00:00
if(!wav_find_chunk(fd, "RIFF")) {
printf("ERROR: Could not find WAV RIFF chunk.\n");
return NULL;
}
Riff riff;
fread(&riff, sizeof(Riff), 1, fd);
2015-01-26 03:04:27 +00:00
if(!wav_find_chunk(fd, "fmt ")) {
printf("ERROR: Could not find WAV format chunk.\n");
return NULL;
}
Format format;
fread(&format, sizeof(Format), 1, fd);
2015-01-26 03:04:27 +00:00
if(!wav_find_chunk(fd, "data")) {
printf("ERROR: Could not find WAV data chunk.\n");
return NULL;
}
Data data;
2015-01-26 03:04:27 +00:00
fread(&(data.chunkId), sizeof(data.chunkId), 1, fd);
fread(&(data.chunkSize), sizeof(data.chunkSize), 1, fd);
data.data = (u8*) malloc(data.chunkSize);
fread(data.data, 1, data.chunkSize, fd);
fclose(fd);
WAV* wav = (WAV*) malloc(sizeof(WAV));
wav->riff = riff;
wav->format = format;
wav->data = data;
return wav;
2015-01-26 03:04:27 +00:00
}
void wav_free(WAV* wav) {
if(wav != NULL) {
free(wav->data.data);
free(wav);
}
}