有人可以告诉我这段代码中我做错了什么吗?它可以编译,但不能正确反转音频文件。它确实通过不正确地使音频清晰来反转文件类型。这是 cs50x 课程的问题集 4。我相信 TODO #8 有问题。
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "wav.h"
int check_format(WAVHEADER header);
int get_block_size(WAVHEADER header);
int main(int argc, char *argv[])
{
// Ensure proper usage
// TODO #1
if (argc != 3)
{
printf("entre input and output file names\n");
return 1;
}
// Open input file for reading
// TODO #2
char *infile = argv[1];
char *outfile = argv[2];
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
printf("error opening file\n");
fclose(inptr);
return 2;
}
// Read header
// TODO #3
WAVHEADER wv;
fread(&wv, sizeof(WAVHEADER), 1, inptr);
long position = ftell(inptr);
// Use check_format to ensure WAV format
// TODO #4
if (check_format(wv) == -1)
{
printf("input is not a wav.h file\n");
fclose(inptr);
return 3;
}
// Open output file for writing
// TODO #5
FILE *outptr = fopen(outfile, "wb");
if (outptr == NULL)
{
printf("error opening output file\n");
fclose(outptr);
fclose(inptr);
return 4;
}
// Write header to file
// TODO #6
fwrite(&wv, sizeof(WAVHEADER), 1, outptr);
// Use get_block_size to calculate size of block
// TODO #7
int blsize = get_block_size(wv);
// Write reversed audio to file
// TODO #8
DWORD bufferSize = wv.subchunk2Size;
int16_t *audio = malloc(bufferSize);
fseek(inptr, blsize, SEEK_END);
fseek(outptr, position, SEEK_SET);
for (int i = 0; i < bufferSize / blsize; i++)
{
fread(&audio[i], blsize, 1, inptr);
fseek(inptr, (-2) * blsize, SEEK_CUR);
fwrite(&audio[i], blsize, 1, outptr);
}
fclose(outptr);
fclose(inptr);
free(audio);
}
int check_format(WAVHEADER header)
{
// TODO #4
char elmnts[] = {'W', 'A', 'V', 'E', '\0'};
for (int i = 0; i < 4; i++)
{
if (elmnts[i] != header.format[i])
{
return -1;
}
}
return 0;
}
int get_block_size(WAVHEADER header)
{
// TODO #7
int blsize = header.numChannels * (header.bitsPerSample / 8);
return blsize;
}
我不知道该怎么办。请帮忙。
我同意你的怀疑——一个坚实的痛点似乎是 TODO #8 这是一个搜索问题...请尝试这种方法:
// Write reversed audio to file
// TODO #8
DWORD bufferSize = wv.subchunk2Size;
DWORD readPosition; /* Added readPosition*/
fseek(inptr, 0, SEEK_END); /* Seek to EOF */
readPosition = ftell(inptr); /* Set readPosition to EOF*/
int16_t *audio = malloc(bufferSize);
fseek(outptr, position, SEEK_SET);
/* Also please double check this limit -> ( bufferSize / blsize )
** (might be fine, not sure) */
for (int i = 0; i < bufferSize / blsize; i++)
{
readPosition -= blsize; /* Decrement readPosition by block size*/
fseek(inptr, readPosition, SEEK_SET); /* Seek to read position */
fread(&audio[i], blsize, 1, inptr);
fwrite(&audio[i], blsize, 1, outptr);
}