Open
Description
Hello, AI provided me with this code, which correctly uses libmad to retrieve the duration of an MP3 file.
Could someone help verify if this implementation is optimal or if there are any edge cases I should consider?
`
#include <mad.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
if(argc != 2) return 1;
FILE* file = fopen(argv[1], "rb");
if(!file) return 1;
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
unsigned char* buffer = (unsigned char*)malloc(size);
fread(buffer, 1, size, file);
fclose(file);
struct mad_stream stream;
struct mad_frame frame;
mad_stream_init(&stream);
mad_frame_init(&frame);
mad_stream_buffer(&stream, buffer, size);
long total_samples = 0;
unsigned int sample_rate = 0;
while(1) {
if(mad_frame_decode(&frame, &stream)) {
if(!MAD_RECOVERABLE(stream.error)) break;
continue;
}
if(sample_rate == 0) sample_rate = frame.header.samplerate;
total_samples += MAD_NSBSAMPLES(&frame.header);
}
double duration = (sample_rate > 0) ? (double)total_samples / sample_rate : 0.0;
if(duration > 0) {
printf("Duration: %.2f seconds\n", duration);
}
free(buffer);
mad_frame_finish(&frame);
mad_stream_finish(&stream);
return 0;
}
`
Metadata
Metadata
Assignees
Labels
No labels