Symfony2 – how to send video response to twig view

In this tutorial we will learn a very basic tip, how to send a video to twig view, through a controller.

To perform this operation, I assume (for your comfort) that you work with knpGaufretteBundle (filesystem abstraction layer) and LiipImagineBundle if you need it. If you don’t have any of these packages, still get a look to Symfony Filesystem component documentation.

We will only use Symfony based Filesystem component. Let’s see our php function

     * Respond video source to twig view
     * @param object $video Video entity object
     * @return \Symfony\Component\HttpFoundation\Response
    public function videoResponse($video){
        //Target service filesystem
        $filesystem     = (object) $this->get('your_service_filesystem');
        //Get the video filetype
        $fileType       = (string) $video->getFiletype();
        //Fetch binary video content
        $content        = (string) $filesystem->read($video->getPath());
        return new Response($content, 200, array(
            'Content-Type'        => 'video/' . $fileType           

What we’ve done here is that, we sent an http header with a content type of the video (mp4, ogg, webm…) containing the video content. When you’ll access this url, the video will be directly accessible in your browser.

In your twig, just write this:

    <video id='video' autoplay loop controls='true'>
        <source src="{{my_video_path}}"  type="video/mp4">
        <source src="{{my_video_path}}" type="video/webm">
        <source src="{{my_video_path}}"  type="video/ogg">


That’s all :).

Symfony2 – how to send video response to twig view

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s