Reputation:
I am trying to edit a wav file using c++ by directly reading its binary data. I have written the file's header as follows:
struct header{
char chunk_id[4];
int chunk_size;
char format[4];
char subchunk1_id[4];
int subchunk1_size;
short int audio_format;
short int num_channels;
int sample_rate;
int byte_rate;
short int block_align;
short int bits_per_sample;
char subchunk2_id[4];
int subchunk2_size;
};
Now how to compute the maximum duration of the sound track assuming that the header's data is already loaded in some variable?
Upvotes: 1
Views: 3059
Reputation: 42165
Assuming a duration in seconds (rounded down) is good enough, you can simply use
int durationInSeconds(struct header* hdr)
{
int numSamples = hdr->subchunk2_size /
(hdr->num_channels * (hdr->bits_per_sample/8));
int durationSeconds = numSamples / hdr->sample_rate;
return durationSeconds;
}
subchunk2_size
gives you the number of bytes of audio data. Dividing this by the product of the number of samples and byte rate (note: bits_per_sample
gives you the number of bits in a single sample for a single channel - this is different from byte_rate
in header
) gives you a total number of samples.
sample_rate
is the number of samples per second so dividing the total number of samples by this gives you the total duration in seconds.
Upvotes: 6