跳到主要內容

[操作記錄] 在 Mac上安裝 Nginx 以實現 HLS Stream


因為課堂需要,所以在此簡單紀錄安裝 Nginx 的過程。

首先,在 Terminal 輸入以下指令來安裝 Homebrew:
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

若要移除安裝,則執行以下指令:
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

升級 Homebrew:
$ brew update

接著就是開始安裝 Nginx:
$ brew tap denji/nginx

我們需要用到 nginx-rtmp-module,所以接著輸入
$ brew install nginx-full --with-rtmp-module


設定 RTMP 與支援 HLS,打開位於 /usr/local/etc/nginx 的 nginx.conf 新增以下文字:
在event 跟 http 之間輸入:
event{
..
}

rtmp {
    server {
        listen 1935;
        chunk_size 4000;
        application hls {
            live on;
            hls on;
            hls_path /tmp/hls;
            hls_continuous on;
            hls_cleanup off;
        }
    }
}

http{
..
}

在 http 裡輸入:
http{
..
    location / {
    ..
    }

    location /hls {
        # Serve HLS fragments
        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
        }
        root /tmp;
        add_header Cache-Control no-cache;
        }

..
}



因為對文件做了更改,所以需要重新載入。
$ nginx -s reload

再來需要安裝播放器 ffmpeg,將我們的檔案分割成串流所需要的.m3u8 及 .ts。
$ brew install ffmpeg

轉換檔案:
$ ffmpeg -i FILE_NAME -g 60 -hls_time 2 -hls_list_size 0 playlist.m3u8

接著移動轉好的檔案到tem/hls下,才能正常串流。
$ cp platlist* /tmp/hls/

接著就可以從瀏覽器看到影片串流囉!
$ http://localhost:8080/hls/playlist.m3u8

補充幾個Nginx的用法:

啟動 Nginx:
$ nginx -s start

關閉 Nginx(可能需要清理瀏覽器暫存):
$ nginx -s stop


文章參考:
https://medium.com/@ponychen/在-osx-上透過-homebrew-安裝-nginx-與啟用-hls-功能-9b5f02130f2
https://yuhanle.github.io/2018/03/12/live-broadcast-rtmp/
http://stonefishy.github.io/blog/2015/12/05/using-nginx-in-mac-os-x/

留言