JavaScript - html 音频的小时、分钟、秒、毫秒到浮点秒

JavaScript - hours, minutes, seconds, millisecond to floating point seconds for html audio

我需要将包含小时、分钟、秒和毫秒的字符串 "hh:mm:ss:mil" 转换为 HTML 音频播放器用于 currentTime 的浮点数。

我找不到执行此操作的任何转换算法!我发现最接近的转换为整数秒,而我需要这样的东西

“00:00:38:000”-> 38.0(不是 2280)

"01:15:02:773" -> 4502.773

到目前为止我的代码 - 但它是错误的

function time2secs(time) {
    // 00:03:30 -> 3.5 seconds
    var t = time.split(':');
    if (t.length < 4) t[3] = 0; // if a missing millisecs, then set it to 0

    var seconds = parseInt(t[0]) * 60 * 60 + parseInt(t[1]) * 60 + parseInt(t[2]) + parseInt(t[3]) / 1000;

    return seconds / 60;
}

试试这个

function timeToSec(time){
    var arr=time.split(":");
  return parseInt(arr[0])*3600+ parseInt(arr[1])*60+ parseInt(arr[2])+ parseInt(arr[3])*0.1000
}
console.log(timeToSec("00:00:38:000" ))
console.log(timeToSec("01:15:02:773" ))

此代码是否按您预期的那样工作?

function time2secs(time) {
    var t = time.split(':');
    if (t.length < 4) t[3] = 0;

    let second = (parseInt(t[0]) * 60 * 60) + (parseInt(t[1]) * 60) + parseInt(t[2]) + (parseInt(t[3]) / 1000);
    return t[3] == 0 ? second + ".0" : second;

}