You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET6 Linux环境下C#读取音频文件时长失败的解决方案咨询

跨平台读取音频文件时长的可行方案

方案1:TagLibSharp(无原生依赖,多格式支持)

TagLibSharp是纯.NET实现的跨平台媒体元数据处理库,支持MP3、WAV、FLAC、OGG等绝大多数常见音频格式,无需额外安装系统依赖,适合ASP.NET Core服务器端场景。

  • 安装NuGet包:Install-Package TagLibSharp
  • 核心代码示例:
using TagLib;

public static TimeSpan GetAudioDuration(string filePath)
{
    using var file = TagLib.File.Create(filePath);
    return file.Properties.Duration;
}

该方法直接返回音频时长,自动适配不同格式,无平台兼容性问题,是最简洁的解决方案。

方案2:FFmpeg命令行调用(全格式兼容,适合复杂场景)

如果需要支持极小众音频格式,FFmpeg是终极选择,Linux服务器可通过包管理器快速安装,兼容性拉满。

  • 服务器安装FFmpeg:
    Ubuntu/Debian:sudo apt update && sudo apt install ffmpeg -y
    CentOS/RHEL:sudo dnf install ffmpeg -y
  • 代码调用示例:
using System.Diagnostics;

public static TimeSpan GetAudioDurationWithFfmpeg(string filePath)
{
    var processStartInfo = new ProcessStartInfo
    {
        FileName = "ffmpeg",
        Arguments = $"-i \"{filePath}\" -show_entries format=duration -v quiet -of csv=\"p=0\"",
        RedirectStandardOutput = true,
        UseShellExecute = false,
        CreateNoWindow = true
    };

    using var process = Process.Start(processStartInfo);
    process.WaitForExit();
    var output = process.StandardOutput.ReadToEnd().Trim();
    
    if (double.TryParse(output, out var durationSeconds))
    {
        return TimeSpan.FromSeconds(durationSeconds);
    }
    
    throw new InvalidOperationException("无法读取音频时长");
}

通过FFmpeg命令行参数直接提取时长,解析输出结果即可。缺点是需要服务器预装FFmpeg,但胜在支持所有音频格式。

方案3:MP3专属轻量实现(无外部依赖,仅MP3)

如果只需要处理MP3文件,可直接解析MP3帧头信息计算时长,无需任何第三方库,适合资源受限场景。

核心代码示例:

public static TimeSpan GetMp3Duration(string filePath)
{
    using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[4];
    int frameCount = 0;
    int sampleRate = 0;

    while (stream.Position < stream.Length - 4)
    {
        stream.Read(buffer, 0, 4);
        // 检查MP3帧头同步字(0xFFE0及以上)
        if ((buffer[0] == 0xFF) && ((buffer[1] & 0xE0) == 0xE0))
        {
            // 提取采样率
            int sampleRateIndex = (buffer[2] >> 2) & 0x03;
            int[] sampleRates = { 44100, 48000, 32000, 0 };
            sampleRate = sampleRates[sampleRateIndex];
            
            // 提取帧长度并跳过当前帧剩余部分
            int frameLength = ((buffer[2] & 0x03) << 11) | (buffer[3] << 3) | ((buffer[2] & 0x0C) >> 2);
            stream.Position += frameLength - 4;
            frameCount++;
        }
        else
        {
            stream.Position -= 3; // 回退字节继续查找帧头
        }
    }

    if (sampleRate == 0 || frameCount == 0)
        throw new InvalidOperationException("无法解析MP3文件");

    // MP3每帧含1152个样本,计算总时长
    return TimeSpan.FromSeconds((frameCount * 1152.0) / sampleRate);
}

该方法直接操作文件流解析MP3帧,无任何依赖,但仅支持MP3格式,适合特定业务场景。


原方案失效原因说明

  • NAudio:依赖Windows专属的Msacm32.dll音频编码库,Linux环境下不存在,必然报错。
  • LibVLCSharp:需要完整的VLC运行时依赖,包括libX11这类图形界面库,服务器环境通常无桌面组件,即使安装VLC SDK也会因缺少图形依赖失败,不适合无头服务器场景。

内容的提问来源于stack exchange,提问作者mobearette

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 16:20:47