Play video with subtitles with html5 player
The <video> tag is the easiest way to play a video on the browser. In this article we see how we can add also subitles in the video.
Browsers support different types of video types, better options are webm or mp4.
If you need to convert a video file in another type, you can use the ffmpeg command:
ffmpeg -i input.mkv -f webm -c:v libvpx -b:v 1M -acodec libvorbis ouput.webm -hide_banner
ffmpeg -i input.mkv -f mp4 -vcodec libx264 -preset fast -profile:v main -acodec aac output.mp4 -hide_banner
Then you need to prepare the subtitles in vtt format. If you have srt file, you can convert it with ffmpeg:
ffmpeg -i subtitle.srt subtitle.vtt
Here is the code to place on your html file:
<video controls preload="metadata">
<source src="output.mp4" type="video/mp4">
<track label="English" kind="subtitles" srclang="en" src="subtitles.vtt" default>
</video>
- controls attribute will display the controls buttons for the video
- preload attribute loads the video metadata when the page loads
- default attribute in <track> will load the subtitles automatically
If subtitles wont play, it may be that your server serves them as plain text and not as text/vtt type. You may get this error on brwoser console: "Resource interpreted as TextTrack but transferred with MIME type text/plain:"
In Apache you can add this line inside .htaccess in the same or above folder, that your vtt file is placed.
AddType text/vtt .vtt