Subtitle by current time

My problem in the function below is the “subtitles” variable.

I want to put a file with the same code: "[{start: 0,end: 2.499,text: 'Start at .5 secs end at 2 secs'},{start: 2.500,end: 5.000,text: 'Start at 2.5 secs end at 5 secs'},{start: 5.000, end: 10.000,text: 'Start at 5 secs end at 10 secs'}];"

Preferably file in txt format, but it can be any format. it has to be “current time” based. If you have any time based VTT or SRT script, it would be of great help.

Thank you in advance.

<script src="https://player.vimeo.com/api/player.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<iframe id="player1" src="https://player.vimeo.com/video/357223218" width="630" height="354" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" data-ready="true"></iframe>
<p id="subtitle"></p>

<script>
    function handleSubtitles(currentTime) {
        // If there is an active subtitle and it should be hidden
        if (activeSubtitle !== null && (currentTime >= subtitles[activeSubtitle].end || currentTime < subtitles[activeSubtitle].start)) {
            subtitleDisplay.innerText = ''; // Hide subtitle
            activeSubtitle = null;
        }

        // If there is no active subtitle
        if (activeSubtitle === null) {
            for (var i = 0; i < subtitleCount; i++) {
                if (currentTime >= subtitles[i].start && currentTime < subtitles[i].end) {
                    subtitleDisplay.innerText = subtitles[i].text; // Show subtitle
                    activeSubtitle = i;
                    break;
                }
            }
        }
    }

    const video = document.getElementById('player1');
    const subtitleDisplay = document.getElementById('subtitle');

    let activeSubtitle = null;

    subtitles = [{start: 0, end: 2.499, text: 'Start at .5 secs end at 2 secs'}, {start: .500, end: 5.000, text: 'Start at 2.5 secs end at 5 secs'}, {start: 5.000, end: 10.000, text: 'Start at 5 secs end at 10 secs'}];

    const subtitleCount = subtitles.length;

    var iframe = $('#player1')[0];
    var player = new Vimeo.Player(iframe);

    if (subtitleCount) {
        player.on('timeupdate', function (data) {
            const str = data.seconds;
            handleSubtitles(str);
        });
    }
</script>

Demo VTT:
english_subtitle.zip (413 Bytes)

So a .json file. Sure. You’ve got jQuery loaded, so use it’s shorthands.

$.getJSON("MyFile.json", function(data) { subtitles = data; });

(Note that MyFile.json must be a web-accessible file. This is NOT accessing the local harddrive!)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.