8000 How to get mp3 duration with libmad? · Issue #1 · sezero/libmad · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
How to get mp3 duration with libmad? #1
Open
@SwartzBushnell

Description

@SwartzBushnell

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0