用FFmpeg SDK计算MP3文件的时长

来源:互联网 发布:足迹软件 编辑:程序博客网 时间:2024/05/29 10:17

说明

  • 首先需要编译FFmpeg,这个网上已经有很多资料了,这里略过。可参见:VS编译FFmpeg
  • 关于FFmpeg SDK的使用,可以参见:An ffmpeg and SDL Tutorial

计算MP3文件时长

主要利用 avformat_find_stream_info读取文件信息,AVFormatContext中的成员变量duration用来描述MP3文件的时长。注意duration的值为实际秒数*AV_TIME_BASE

extern "C"{#include "libavformat/avformat.h"};double duration(const char *filename){    av_register_all();    AVFormatContext *pFormatCtx = NULL;    // Open video file    if(avformat_open_input(&pFormatCtx, filename, NULL, NULL) != 0)    {        return -1; // Couldn't open file    }    avformat_find_stream_info(pFormatCtx, NULL);    double duration = (double)pFormatCtx->duration / AV_TIME_BASE;    avformat_close_input(&pFormatCtx);    avformat_free_context(pFormatCtx);    return duration;}
1 0