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

在C#的LibVLCSharp中如何正确获取并显示视频时间?

视频播放时长与进度显示修复方案

原代码

public Form1()
{
    InitializeComponent();

    Core.Initialize();
    this.KeyPreview = true;
    this.KeyDown += new KeyEventHandler(ShortcutEvent);
    oldVideoSize = videoView1.Size;
    oldFormSize = this.Size;
    oldVideoLocation = videoView1.Location;
    //VLC stuff
    _libVLC = new LibVLC();
    _mp = new MediaPlayer(_libVLC);
    videoView1.MediaPlayer = _mp;

    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    TimeSpan Percent = TimeSpan.FromSeconds(_mp.Position);
    label1.Text = Percent.ToString(@"hh\:mm\:ss");

    TimeSpan time = TimeSpan.FromSeconds(_mp.Time);
    label2.Text = time.ToString(@"hh\:mm\:ss");

    TimeSpan length = TimeSpan.FromSeconds(_mp.Length);
    label3.Text = length.ToString(@"hh\:mm\:ss");
}

存在的问题

  • 百分比进度失效:_mp.Position返回的是0到1的播放比例(比如播放到一半就是0.5),不是秒数,直接转TimeSpan完全错误
  • 当前播放时间更新异常:_mp.Time的单位是毫秒,用FromSeconds转换会把实际时长缩小1000倍,导致显示节奏混乱
  • 总时长格式错误:_mp.Length同样是毫秒单位,用FromSeconds转换会让总时长显示远小于实际值

修复后的代码

private void timer1_Tick(object sender, EventArgs e)
{
    // 处理百分比进度:计算已播放时长占总时长的比例,转成百分比显示
    if (_mp.Length > 0)
    {
        double progressPercent = (_mp.Time / (double)_mp.Length) * 100;
        label1.Text = $"{progressPercent:F1}%"; // 保留1位小数的百分比格式
    }
    else
    {
        label1.Text = "0%"; // 视频未加载完成时显示默认值
    }

    // 处理当前播放时间:用毫秒单位转TimeSpan
    TimeSpan currentTime = TimeSpan.FromMilliseconds(_mp.Time);
    label2.Text = currentTime.ToString(@"hh\:mm\:ss");

    // 处理总时长:用毫秒单位转TimeSpan
    TimeSpan totalLength = TimeSpan.FromMilliseconds(_mp.Length);
    label3.Text = totalLength.ToString(@"hh\:mm\:ss");
}

额外说明

  • 添加_mp.Length > 0的判断是为了避免视频未加载时出现除以0的错误
  • 如果想把进度改成「已播放时长/总时长」的格式,可将label1的赋值改成:
    label1.Text = $"{currentTime.ToString(@"hh\:mm\:ss")}/{totalLength.ToString(@"hh\:mm\:ss")}";
    

内容的提问来源于stack exchange,提问作者מכון כתר תורה

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:11:54