You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

VLC Lua扩展开发:如何获取当前播放时间与文件总时长

在VLC Lua扩展中获取播放时间与总时长

嘿,作为刚入坑VLC Lua扩展的新手,我太懂你翻官方README找不到解决方案的郁闷了!其实VLC的Lua API里藏着对应的方法,我来给你一步步讲清楚:

核心思路

VLC的Lua扩展可以通过访问输入对象(input)的内部变量来获取播放相关的时间数据,主要用到vlc.object.input()获取当前输入,再用vlc.var.get()读取对应属性。

具体实现步骤

  • 获取当前播放时间

    1. 先拿到当前的输入对象:local input = vlc.object.input()
    2. 检查是否有正在播放的媒体(不然会报错):if not input then ... end
    3. 读取当前播放时间(返回值为毫秒):local current_time = vlc.var.get(input, "time")
  • 获取媒体总时长
    同样基于输入对象,读取length变量即可:local total_length = vlc.var.get(input, "length"),返回值也是毫秒。

完整示例代码

把这些逻辑放到你的菜单激活回调里,比如:

function activate()
    -- 获取当前播放的输入对象
    local input = vlc.object.input()
    
    -- 处理没有媒体播放的情况
    if not input then
        vlc.dialogs.error("当前没有正在播放的媒体文件!")
        vlc.msg.warn("尝试获取播放时间失败:无活跃输入")
        return
    end

    -- 读取时间数据(毫秒)
    local current_ms = vlc.var.get(input, "time")
    local total_ms = vlc.var.get(input, "length")

    -- 转换为秒(可选,方便阅读)
    local current_sec = current_ms / 1000
    local total_sec = total_ms / 1000

    -- 弹出对话框展示
    vlc.dialogs.info(
        string.format("播放状态:\n当前时间: %.2fs\n总时长: %.2fs", current_sec, total_sec)
    )
    -- 终端输出日志
    vlc.msg.info(
        string.format("[扩展日志] 当前播放时间: %.2fs | 总时长: %.2fs", current_sec, total_sec)
    )
end

注意事项

  • 一定要先判断input是否为nil,如果没有播放任何媒体就调用vlc.var.get()会导致脚本崩溃。
  • 返回的时间单位是毫秒,根据需求可以自行转换为秒、时分秒等格式(比如用数学运算拆分小时、分钟、秒)。

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

火山引擎 最新活动