Domanda

How to access sub-chunks's data of .wav file? I've been trying to copy binary data (first 44 bytes) to a struct variable (size of 44 bytes). But there is a problem: I'm convinced that I'd copied binary data from the file input to a struct named hdr.

But when I'm trying to display hdr.ChunkID which contains "RIFF" (array of char) it doesn'y print "RIFF".. It prints nothing.

#include <stdio.h>
#include <stdlib.h>

typedef struct FMT
{
    char        Subchunk1ID[4];
    int         Subchunk1Size;
    short int   AudioFormat;
    short int   NumChannels;
    int         SampleRate;
    int         ByteRate;
    short int   BlockAlign;
    short int   BitsPerSample;

} fmt;

typedef struct DATA
{
    char        Subchunk2ID[4];
    int         Subchunk2Size;
    int         Data[441000]; // 10 secs of garbage. he-he)
} data;

typedef struct header
{
    char        ChunkId[4];
    int         ChunkSize;
    char        Format[4];
    fmt         S1;
    data        S2;
} Header;



int main()
{
    FILE *input = fopen("in.wav", "rb");
    FILE *output = fopen("out.wav", "wb");

    unsigned char buf[64];
    Header hdr;

    if(input == NULL)
    {
        printf("Unable to open wave file\n");
        exit(EXIT_FAILURE);
    }

    fread(&buf, sizeof(char), 64, input);
    fwrite(&buf, sizeof(char), 64, output);

    fread(&hdr, sizeof(char), 64, output);
    printf("\n>>> %s", hdr.ChunkId);         /* Here it is. */

    fclose(input);
    fclose(output);

    return 0;
}

Cannot understand what is wrong.

È stato utile?

Soluzione

Because you try to read from an write-only file handle. Read into hdr with the first fread call. No need for the buf array (or a second read):

Header hdr;

/* Opening files ... */

fread(&hdr, 1, 64, input);
fwrite(&hdr, 1, 64, output);

printf("\n>>> %4.4s", hdr.ChunkId); 

/* ... */

Also note that hdr.ChunkID will not be terminated as a string, so printing it as a string might print seemingly random characters after the header. This is why I added field length and precision in the printf call.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top