Stream MP4 from S3 to a HTML page

Written by

Convert MP4 to HLS

A mp4 cannot be read directly from HTML. For that it needs to be converted to a HLS file. HLS stands for HTTP Live Streaming.

Below the command to convert a file from mp4 to hls. Open a shell to execute this command. Make sure to install FFmpeg first.

ffmpeg -i filename.mp4 \
  -codec: copy \
  -hls_time 10 \
  -hls_list_size 0 \
  -f hls \
  filename.m3u8

Connect to your amazon account and create a new bucket. Then, upload your hls file with generated sub files .ts

Go in the bucket permissions, scroll down and edit the bucket policy with this one.

my-s3-bucket should changed to the name of your bucket and save the changes.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadForGetBucketObjects",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::my-s3-bucket/*"
        }
    ]
}

Scroll down and add this cors policy for the bucket permission.

You can keep AllowedOrigins to * on development mode but you will need a specific domain name when deploying your application in production.

[
    {
        "AllowedHeaders": [
            "Content-Type",
            "Authorization"
        ],
        "AllowedMethods": [
            "GET"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "x-custom-header"
        ],
        "MaxAgeSeconds": 3000
    }
]

Generate a presigned url for the file “filename.m4ua” and copy the url into your a index.html

<html>
<head>
   <link href="https://vjs.zencdn.net/7.19.2/video-js.css" rel="stylesheet" />
</head>
<body>
   <video
      id="my-video"
      class="video-js vjs-big-play-centered vjs-theme-sea"
      controls
      preload="auto"
      fluid="true"
      poster="https://www.tutorialspoint.com/videos/sample.png"
      data-setup='{}'
   >
   </video>
   <script src="https://vjs.zencdn.net/7.17.0/video.min.js">
   </script>
   <script src="https://unpkg.com/videojs-contribhls/dist/videojs-contrib-hls.js"></script>
   <script>
      var player = videojs('my-video');
      player.src({
         src:'presigned-url-here',
         type: 'application/x-mpegURL'
      });
   </script>
</body>
</html>

Et voila!