如何基於 Nginx 搭建流媒體服務器

        HLS 是最常見的視頻流媒體協議,HLS 是一種自適應流媒體技術,可以根據用戶的設備和網絡條件對播放媒體內容,以獲得最佳播放性能。

      Nginx RTMP 是一個 Nginx 插件,支持將 RTMP 和 HLS 流添加到媒體服務器。以 ubuntu 爲力,下面介紹如何安裝使用 nginx Rtmp 插件的步驟。

1. 更新 apt 庫

apt-get update

2. 安裝 ffmpeg 等所需要的軟件

apt-get install -y git build-essential ffmpeg libpcre3 libpcre3-dev libssl-dev zlib1g-dev

3. 下載 RTMP 模塊

git clone https://github.com/sergey-dryabzhinsky/nginx-rtmp-module.git

4. 下載並解壓 Nginx

wget http://nginx.org/download/nginx-1.17.6.tar.gztar -xf nginx-1.17.6.tar.gzcd nginx-1.17.6

5. 配置 Nginx
拷貝一份 nginx 配置文件出來

mv /usr/local/nginx/conf/nginx.confnano /usr/local/nginx/conf/nginx.conf


將以下內容複製到 nginx.conf 文件中

events {
  worker_connections 1024;
}
# RTMP configuration
rtmp {
  server 
  {
    listen 1935; 
    # Listen on standard RTMP 
    portchunk_size 4000;
    application show 
    {
      live on;
      # Turn on HLS
      hls on;
      hls_path /mnt/hls/;
      hls_fragment 3;
      hls_playlist_length 60;
      # disable consuming the stream from nginx as rtmpdeny 
      play all;
    }
  }
}
http {
  sendfile off;
  tcp_nopush on;
  directio 512;
  default_type application/octet-stream;
  server {
    listen 8080;
    location / {
      # Disable cache
      add_header 'Cache-Control' 'no-cache';
      # CORS setup
      add_header 'Access-Control-Allow-Origin' '*' always;
      add_header 'Access-Control-Expose-Headers' 'Content-Length';
      # allow CORS preflight requests
      if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
      }
      types {
        application/dash+xml mpd;
        application/vnd.apple.mpegurl m3u8;
        video/mp2t ts;
      }
      root /mnt/;
    }
  }
}

6. 啓動 Nginx

/usr/local/nginx/sbin/nginx

7. 測試

該服務器可以從各種來源進行流式傳輸,包括靜態文件、網絡攝像頭等。由於上面的步驟中安裝了 ffmpeg,我們可以將 example-vid.mp4 視頻文件流式傳輸到 http 服務 http://localhost/show/stream。

ffmpeg -re -i example-vid.mp4 -vcodec libx264 -vprofile baseline -g 30 -acodec aac -strict -2 -f flv rtmp://localhost/show/stream

8. 最後

根據服務的需求,可以將 http 服務集成到您的應用程序或者網頁中。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/Rsu6XB9mN0hOBw-F1-k4cw