A simple application example of m3u8 video playback based on the Web

A simple application example of m3u8 video playback based on the Web

Implementation ideas

To convert video (MP4, etc.) to M3U8 video services, you can follow the steps below:

  1. Convert video (MP4, etc.) to M3U8: In the service, use an appropriate tool (eg FFmpeg) to convert the received video (MP4, etc.) to M3U8 format. This will generate an M3U8 file containing the video stream and the corresponding segment (TS) file.

  2. Provide side-by-side broadcasting service: store the generated M3U8 files and segment files in an appropriate location (such as a folder on the server or in a cloud storage service). Then, by providing the URLs of these files to the front-end, the front-end can load and play the video segment by segment in a stream-as-you-go manner.

  3. Implement M3U8 player on the front end: On the front end, you can use the existing video player library (such as video.js, plyr.js, etc.) or the player library based on the HLS (HTTP Live Streaming) protocol (such as hls.js) to implement the M3U8 video player. These libraries can load and play videos by providing URLs to M3U8 files.

1. Convert video (MP4, etc.) to M3U8 video

Use Python to convert MP4 video to M3U8 video, follow the steps below:

  1. Install required libraries: First, make sure you have installed required libraries. In Python, ffmpeg-pythonthe library can be used to interact with FFmpeg to perform video conversion operations. The library can be installed with the following command:
pip install ffmpeg-python
  1. Import the library and set up the conversion function: In the Python code, import ffmpegthe module and create a function for converting MP4 to M3U8. Here is a sample code:
import ffmpeg

def convert_mp4_to_m3u8(input_file, output_file):
    """
    Converts an MP4 file to an M3U8 file using ffmpeg.
    Args:
        input_file (str): The path to the input MP4 file.
        output_file (str): The path to the output M3U8 file.
    Returns:
        bool: True if the conversion was successful, False otherwise.
    """
    try:
        ffmpeg.input(input_file).output(output_file, format='hls', hls_time=10, hls_segment_type='mpegts').run()
        return True
    except ffmpeg.Error as e:
        print(f"An error occurred during video conversion: {
      
      e.stderr}")
        return False

In this sample code, convert_mp4_to_m3u8the function accepts an input file path and an output file path as parameters. It uses FFmpeg to convert input files to M3U8 format and outputs segment (TS) files to the specified output file path.

2. Implement HTTP server to provide access to M3U8 video

http.serverMethod 1. Use the module in the Python standard library

This module provides a simple HTTP server that handles GET and HEAD requests and can serve static files to clients.

The following is a simple sample code that can start an HTTP server and provide clients with access to resources such as videos:

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

In this example, a handler is created http.server.SimpleHTTPRequestHandlerthat handles GET and HEAD requests and serves static files to clients. Then, socketserver.TCPServercreate a TCP server with , and pass the handler to it. Finally, call serve_forever()the method to start listening for requests from clients.

Put resources such as videos in the root directory of the server, for example ./video.m3u8, the client can access through a browser http://localhost:8000/video.m3u8to obtain the resources. Clients can also use other HTTP client programs (such as curlor wget) to access resources.

However, it should be noted that this method is only suitable for serving small static files. If you want to serve resources such as large videos, it is best to use dedicated server software to handle them, such as Apache or Nginx.

Method 2. Use the Flask framework

The Flask framework can provide a more flexible way to access static resources such as videos. Here is a simple sample code:

from flask import Flask, send_from_directory

app = Flask(__name__)

@app.route('/<path:path>')
def static_file(path):
    return send_from_directory('.', path)

if __name__ == '__main__':
    app.run(port=8000)

In this example, a static_fileroute named is defined that handles all HTTP GET requests and send_from_directoryreturns the requested file using the function. Here, the requested file is returned from the current directory. If you want to return files in other directories, you can set send_from_directorythe first parameter of the function to the path of the directory.

To access static resources such as videos, you can place them in the same directory as your Flask application and use relative paths as URLs. For example, if the video file is called video.m3u8, you can use http://localhost:8000/video.m3u8to access the file.

It should be noted that this method is also suitable for small static files. If you want to serve resources such as large videos, it is best to use dedicated server software to handle them, such as Apache or Nginx. In addition, the sample code here only provides the simplest static resource access function. If you need more advanced functions (such as cache control, security, etc.), you can use Flask extensions or implement them yourself in the code.

3. Play M3U8 video on the Web front end

M3U8 is a video streaming playback format based on the HTTP Live Streaming (HLS) protocol (when playing M3U8 files, both the video file and the M3U8 file need to be placed on the HTTP server and accessed through the HTTP protocol). To implement the M3U8 player in the Web front end, you can use some open source JavaScript libraries, such as hls.jsand video.js.

hls.jsIt is an M3U8 player library implemented based on JavaScript. It can automatically detect whether the browser supports HLS, and if not, it will use the Flash player to play. Here is a hls.jssample code using :

<!DOCTYPE html>
<html>
  <head>
    <title>hls.js player example</title>
    <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
  </head>
  <body>
    <video id="video" controls></video>
    <script>
      var video = document.getElementById("video");
      if (Hls.isSupported()) {
      
      
        var hls = new Hls();
        hls.loadSource("http://127.0.0.1:8000/path/to/video.m3u8");
        hls.attachMedia(video);
        hls.on(Hls.Events.MANIFEST_PARSED, function () {
      
      
          // video.play();
        });
      } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
      
      
        video.src = "http://127.0.0.1:8000/path/to/video.m3u8";
        video.addEventListener("loadedmetadata", function () {
      
      
          // video.play();
        });
      }
    </script>
  </body>
</html>

In this example, the library is first imported into the page hls.js. Then, create an HTML5 videoelement and set controlsthe attribute so that the user can control the playback of the video.

Next, use Hls.isSupported()the method to detect whether the browser supports HLS. If supported, create a Hlsobject and use loadSourcethe method to load the M3U8 file. Then, use attachMediathe method to videoattach the element Hlsto the object and MANIFEST_PARSEDstart playing the video when the event fires.

If the browser does not support HLS, check whether application/vnd.apple.mpegurlthe format is supported. If supported, sets the path to the M3U8 file for videothe element's srcattribute and loadedmetadatastarts playing the video when the event fires.

Besides hls.js, there are some other JavaScript libraries that can be used to implement the M3U8 player, eg video.js. Here is an video.jsexample code using :

<!DOCTYPE html>
<html>
  <head>
    <title>video.js player example</title>
    <link href="https://vjs.zencdn.net/8.3.0/video-js.css" rel="stylesheet" />
    <script src="https://vjs.zencdn.net/8.3.0/video.min.js"></script>
  </head>
  <body>
    <video id="video" class="video-js vjs-default-skin" controls></video>
    <script>
      var video = videojs("video", {
      
      
        techOrder: ["html5", "flash"],
        sources: [
          {
      
      
            src: "http://127.0.0.1:8000/path/to/video.m3u8",
            type: "application/x-mpegURL",
          },
        ],
      });
      // video.play();
    </script>
  </body>
</html>

In this example, video.jsthe CSS and JavaScript files for are included first. Then, an HTML5 element is created videoand classthe attribute is set to it so that video.jsthe default styling of is applied.

Next, use videojsthe function to create a video.jsobject, specifying techOrderthe and sourcesoptions. techOrderoption specifies the sequence of technologies to use when playing the video, and if the browser does not support HLS, the Flash player will be used for playback. sourcesThe option specifies the path and type of the M3U8 file to be played.

Finally, call playthe method to start playing the video.

Guess you like

Origin blog.csdn.net/yzh648542313/article/details/130967891