This is the seventh day of my participation in the First Challenge 2022

Actual case content

Mostly sites are currently using m3u8 file format for video files, cut video file is divided into many small ts file, the user does not need to send broadcast network requests a one-time return the entire video file, but a a back ts file, thus greatly reduce the pressure of the network transmission, but also optimize the user experience feeling, The M3U8 file stores the name and playback order of each TS file. Today’s example is parsing an M3U8 file in Python.

The overall train of thought

M3u8 Wikipedia definition

M3U8 is the Unicode version of M3U, encoded in UTF-8. Both the M3U and M3U8 files are the basis for the HTTP Live Streaming (HLS) protocol format used by Apple, which can be played on devices like iphones and macBooks.

We can open the M3U8 file with Notepad, and the file content and format are as follows:

#EXTM3U # ext-x-version :3 # ext-x-targetDuration :11 # ext-x-media-sequence :0 #EXTINF:4.38, https://e1.monidai.com/20210327/vXaL3ypQ/1000kb/hls/c1wXGS6116000.ts # EXTINF: 2.211, https://e1.monidai.com/20210327/vXaL3ypQ/1000kb/hls/c1wXGS6116001.ts # EXTINF: 7.383, https://e1.monidai.com/20210327/vXaL3ypQ/1000kb/hls/c1wXGS6116002.ts ...Copy the code

From which we can get a general idea of the m3u8 file content, it gives the specific address and name for each ts file, this is the best situation, sometimes it will only give each ts file name, then you need we go to the browser’s developer tools – > NetWork for ts file storage site, site location below:

Download the M3U8 file

  • Go directly to the browser developer tools ->NetWork to obtain the URL of the M3U8 file, and then download
  • Send a network request to download the M3U8 file via Python

Parse the M3U8 file to get the TS file path list

Python has a third-party library called m3u8 that can parse m3u8 files.

Batch download TS files from the file list

This step is to use the Request library to send a network request to get the TS file via the url

Download ts files installed in M3U8 in order to merge, store in mp4 file

The code is as follows: