1
I’m making a program to reverse (let it go) a WAV audio given as input, but my program stops working and I can’t find where I’m going wrong.
Follows my code:
header:
#ifndef WAV_H_
#define WAV_H_
#include <stdint.h>
typedef unsigned char byte;
typedef struct riff{
char chunkID[4];
uint32_t chunkSize;
char format[4];
}__attribute__((packed))RIFF;
typedef struct fmt{
char subchunkID[4];
uint32_t subchunkSize;
uint16_t audioFormat;
uint16_t numChannels;
uint32_t sampleRate;
uint32_t byteRate;
uint16_t blockAlign;
uint16_t bitsPerSample;
}__attribute__((packed))FMT;
typedef struct data{
char subChunk2ID[4];
uint32_t subChunk2Size;
}__attribute__((packed)) DATA;
typedef byte RAW_DATA;
#endif /* WAV_H_ */
main:
#include <stdio.h>
#include <stdlib.h>
#include "wav.h"
int main(int argc, char **argv){
if(argv[1] == "\0"){
exit(-1);
}
char *infile_name = argv[1];
FILE *infile = fopen(infile_name, "rb");
if (infile == NULL) {
fprintf(stderr, "Can't open input file %s", infile_name);
exit(1);
}
RIFF *riff_infile = NULL;
FMT *fmt_infile = NULL;
DATA *data_infile = NULL;
riff_infile = (RIFF *) malloc(sizeof(RIFF));
fmt_infile = (FMT *) malloc(sizeof(FMT));
data_infile = (DATA *) malloc(sizeof(DATA));
if (riff_infile == NULL || fmt_infile == NULL || data_infile == NULL){
printf("System out of memory!\n");
exit(-1);
}
fread(riff_infile, sizeof(RIFF), 1, infile);
fread(fmt_infile, sizeof(FMT), 1, infile);
fread(data_infile, sizeof(DATA), 1, infile);
RAW_DATA *samples_infile = NULL;
samples_infile = (RAW_DATA *) malloc(sizeof(RAW_DATA) * ((data_infile->subChunk2Size)));
if (samples_infile == NULL){
printf("System out of memory!\n");
exit(-1);
}
fread(samples_infile, fmt_infile->bitsPerSample/8, (data_infile->subChunk2Size), infile);
riff_infile->chunkID[4]='\0';
fmt_infile->subchunkID[4]='\0';
FILE *outfile;
outfile = fopen("myFile", "w");
RAW_DATA *samples_outfile = NULL;
fmt_infile->subchunkSize = 16;
samples_outfile= (RAW_DATA *) malloc(sizeof(RAW_DATA) * ((data_infile->subChunk2Size)));
int max = (data_infile->subChunk2Size);
int j=0;
while(max >= 0){
samples_outfile[j] = samples_infile[max];
max--;
j++;
}
fwrite(riff_infile, sizeof(RIFF), 1, outfile);
fwrite(fmt_infile, sizeof(FMT), 1, outfile);
fwrite(data_infile, sizeof(DATA), 1, outfile);
fwrite(samples_outfile, sizeof(RAW_DATA) * fmt_infile->bitsPerSample/8, (data_infile->subChunk2Size), outfile);
free(riff_infile);
free(fmt_infile);
free(data_infile);
free(samples_infile);
free(samples_outfile);
fclose(infile);
return 1;
}
outfile = fopen("myFile", "w");
- I think you were supposed to wear"wb"
.– Victor Stafusa
Thank you for answering. I was testing the program on windows and decided to test it on linux and to my surprise it worked. I don’t know what’s wrong with running windows...
– Matheus Toledo
Strange. It doesn’t make much sense that it doesn’t work in windows.
– Victor Stafusa