Skip to content

YT volume controls reset to full volume after any change #2005

@WalidZein

Description

@WalidZein

Whenever you change the volume it resets to full max volume. If you pause the video and change the volume it maintains state. if you then play the video is will reset to full volume.


import { forwardRef, useImperativeHandle, useRef, useState } from "react";

import ReactPlayer from "react-player";


export interface YouTubePlayerRef {
    seekTo: (seconds: number) => void;
}

interface YouTubeWithTimestampsProps {
    videoUrl: string;
    onTimeUpdate?: (currentTime: number) => void;
    initialTime?: number;
}

const YouTubeWithTimestamps = forwardRef<YouTubePlayerRef, YouTubeWithTimestampsProps>(
    ({ videoUrl, onTimeUpdate, initialTime = 0 }, ref) => {
        const playerRef = useRef<HTMLVideoElement | null>(null);
        const [isInitialPlay, setIsInitialPlay] = useState(true);

        useImperativeHandle(ref, () => ({
            seekTo: (seconds: number) => {
                if (!playerRef.current) return;
                playerRef.current.currentTime = seconds;
            },
        }));

        const handleProgress = () => {
            onTimeUpdate?.(playerRef.current?.currentTime || 0);
        };

        const handlePlay = () => {
            if (!isInitialPlay) return;
            setIsInitialPlay(false);
            if (playerRef.current && initialTime > 0) {
                playerRef.current.currentTime = initialTime;
            }
        };

        return (
            <div className="w-full h-full">
                <ReactPlayer
                    ref={playerRef}
                    src={videoUrl}
                    controls
                    width="100%"
                    height="100%"
                    onTimeUpdate={handleProgress}
                    className="rounded-lg"
                    onPlay={handlePlay}
                />
            </div>
        );
    }
);

YouTubeWithTimestamps.displayName = 'YouTubeWithTimestamps';

export default YouTubeWithTimestamps;```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions