code
code

Reputation: 5642

How to capture image of Youtube Video and display on web site

I am interested in creating a website that displays a few "screen captures" on the screen. These "screen captures" can be any image file type (ex: jpeg, png, etc.) I would like to be able to display the first frame screen capture of a Youtube Video. When the user clicks on this, the user will be redirected to the Youtube URL.

How can I retrieve the screen shot or first frame image of a Youtube video, given it's URL? For example: http://www.youtube.com/watch?v=gbcmYbMB9mo Using this, I'd like to have an image of the GoPro camera. Is there an API to capture the first image of the Youtube Video?

Thanks

Upvotes: 1

Views: 5562

Answers (2)

mewc
mewc

Reputation: 1447

Since the video is likely a different origin to where the code is running (your website), it can't be done. A direct video embed can take screenshots with the canvas API.

For youtube and other iframe methods, you'll need serverside processing. Libs exist for this, such as: https://github.com/jsgilberto/youtube-frames

Upvotes: 0

barak manos
barak manos

Reputation: 30146

You can use YouTube IFrame API (see https://developers.google.com/youtube/iframe_api_reference).

Here is an example for playing the video provided in your question (gbcmYbMB9mo):

<body onload="LoadYouTubeIframeAPI()">
    <script type="text/javascript">
        var player = null;
        var playerParams =
        {
            playerVars:
            {
                "enablejsapi":1,
                "origin":document.domain,
                "rel":0
            },
            events:
            {
                "onReady":onPlayerReady,
                "onError":onPlayerError,
                "onStateChange":onPlayerStateChange
            }
        };
        function LoadYouTubeIframeAPI()
        {
            var scriptElement = document.createElement("script");
            scriptElement.src = "http://www.youtube.com/iframe_api";
            var firstScriptElement = document.getElementsByTagName("script")[0];
            firstScriptElement.parentNode.insertBefore(scriptElement,firstScriptElement);
        }
        function onYouTubeIframeAPIReady()
        {
            player = new YT.Player("player",playerParams);
        }
        function onPlayerReady(event)
        {
            player.loadVideoById("gbcmYbMB9mo");
        }
        function onPlayerError(event)
        {
            ...
        }
        function onPlayerStateChange(event)
        {
            if (event.data == YT.PlayerState.ENDED)
            {
                ...
            }
        }
    </script>
</body>

You might need to "play a little" with this code in order to prevent the video from starting automatically...

Upvotes: 1

Related Questions