Home > database >  How to update video's current time when new video is loaded with Tauri and Svelte?
How to update video's current time when new video is loaded with Tauri and Svelte?

Time:08-21

I'm currently creating a windows app with Tauri and Svelte, but ran into some problem. I have a button which when clicked opens the file system to allow a new video to be selected. When a new video is selected I update the VideoStore with the new path. This all works great, and with the below code the video then updates to show the new video, however I also want to reset time = 0 so that the new video starts from the beginning, but that isn't happening here. So if the previous video was at 20 seconds when a new file is being selected, the new video also starts at 20 seconds.

When clicking the Reset button the time changes back to 0, but I would like it to also happen automatically when VideoStore gets updated and the new video is loaded.

I update the time when $VideoStore changes and time is bound to the video's currentTime:

    $: {
        time = 0;
        video_src = `https://asset.localhost/${$VideoStore}`;
    }

The full code:

Video.svelte

<script>
    import VideoStore from "../stores/VideoStore";

    let video_src = $VideoStore;

    let time = 0;
    let duration;
    let paused = true;

    const skip = () => {
        time  = 10;
    };

    function resetTime() {
        time = 0;
    }

    $: {
        time = 0;
        video_src = `https://asset.localhost/${$VideoStore}`;
    }
</script>

<p>{time}</p>
<button on:click={resetTime}>Reset</button>
<button on:click={skip}>Skip 10 seconds</button>
<!-- svelte-ignore a11y-media-has-caption -->
<div >
    {#key video_src}
        <video
            src={video_src}
            width="1280"
            height="720"
            bind:currentTime={time}
            bind:duration
            bind:paused
            controls
        >
        </video>
    {/key}
</div>

OpenButton.svelte

<script>
    import { open } from "@tauri-apps/api/dialog";
    import { documentDir } from "@tauri-apps/api/path";

    import VideoStore from "../stores/VideoStore";

    let filename = "";

    const openfile = async () => {
        const selected = await open({
            directory: false,
            multiple: false,
            defaultPath: await documentDir(),
        });

        filename = selected.replace(/\\/g, "/");
        VideoStore.update(() => {
            return filename;
        });
    };
</script>

<button on:click={openfile}>Open File</button>

CodePudding user response:

The #key probably causes the new instance of the video to be initialized with the old time value. If a src is switched without recreating the element, the time will automatically reset to 0.

REPL

  • Related