首页 > 解决方案 > C ++如何获得mp3文件的持续时间?

问题描述

我正在尝试获取我拥有的 mp3 文件列表的持续时间,它们在 3-6 秒之间变化。

我有一个使用的工作版本ffprobe

#include <iostream>
#include <stdio.h>
#include <string>
#include "process.h"
#include <windows.h>

using namespace std;

string get_audio_file_length(string command)
{
    char buffer[128];
    string result = "";
    // Open pipe to file
    FILE *pipe = popen(command.c_str(), "r");
    if (!pipe)
        return "popen failed!";

    // read till end of process:
    while (!feof(pipe))
    {
        // use buffer to read and add to result
        if (fgets(buffer, 128, pipe) != NULL)
            result += buffer;
    }

    pclose(pipe);
    return result;
}

int main(int argc, const char *argv[])
{
    string file_name = argv[1];
    // depending if ffprobe.exe is in the current directory of the file or added to path variables.
    string length = get_audio_file_length("ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 \"" + file_name + "\"");
    cout << length << endl;
    return 0;
}

编译文件g++ test.cpp -o test并在下面运行会产生以下结果:

>>> test A1.mp3
>>> 5.712000

上面示例的问题是大约需要 15 秒或更长时间才能找到超过 200 个 .mp3 文件的持续时间......

有没有办法优化这个?还是使用纯 C++ 方法而不是使用 ffprobe?

标签: c++mp3

解决方案


推荐阅读