如何在时间轴上确定某事是否开始

How to figure out if something started, on a timeline

我正在移动下面显示的 橙色 颜色的播放头。 绿色浅蓝色深蓝色显示了多个音频片段]灰色种颜色。

移动播放头时,遇到音频片段时,我会播放。

考虑这个伪代码:

playhead.callbackForEveryFrame(doStuffOnEveryFrame)

function doStuffOnEveryFrame(t) {
    // I intend to make sure all clips which should be playing, are actually play!
    if (clip_green.startTime < t) {
        clip_green.play()
    }
    if (clip_lightblue.startTime < t) {
        clip_lightblue.play()
    }
    if (clip_darkblue.startTime < t) {
        clip_darkblue.play()
    }
    if (clip_gray.startTime < t) {
        clip_gray.play()
    }
}

以上代码效率低下。由于它连续调用 play,如果 t 大于剪辑的 startTime

但最好只调用 play 一次,恰好在 t 穿过 startTime 时调用 play

我很难找到检测 t 何时穿过每个音频剪辑的 startTime 的最佳方法。有人有什么建议吗?

您可以将伪代码更改为如下内容:

let events = [clip_green, clip_lightblue, clip_darkblue, clip_gray].flatMap(clip => [
    { time: clip.start_time, do: () => clip.play() }, 
    { time: clip.end_time,   do: () => clip.stop() }
]).sort((a, b) => a.time - b.time)

playhead.callbackForEveryFrame(doStuffOnEveryFrame)

function doStuffOnEveryFrame(t) {
    while (events.length && events[0].time < t) events.shift().do()
}

为了避免在所有操作都完成后调用此回调,您需要一个函数来停止侦听帧更改。类似于:

function doStuffOnEveryFrame(t) {
    while (events.length && events[0].time < t) events.shift().do()
    if (!events.length) playhead.stopCallbackForEveryFrame(doStuffOnEveryFrame);
}