在mac上搭建简单的hls推流服务器
最近公司要有在网页端用hls推流来播放全景视频的需求,难点在于全景播放器的兼容性问题。目前市场上已有成熟的产品是krpano,但是公司希望我去调研下。常年iOS开发的我只好找了两天的开源项目,目前选定videojs来做播放器,结合公司的渲染器来完成。
为了测试demo,先完成在自己的mac上搭建一个hls的推流服务器。一搜索基本全都是用ngnix搭建的,根据各种教程,磕磕绊绊用了半天多时间才搞定。特地把遇到的坑做个记录。
第一步:安装brew
$ /usr/bin/ruby -e"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
第二步:安装nginx服务器
$ brew tap homebrew/nginx
报错:Error: homebrew/nginx was deprecated. This tap is now empty as all its formulae were migrated.
随后换了个github的项目(https://github.com/denji/homebrew-nginx)成功了:
$ brew tap denji/nginx
$ brew install nginx-full --with-upload-module
安装成功之后可查看信息:
$ brew options nginx-full
$ brew info nginx-full
第三步:开始启动服务器
$ sudo nginx
发生错误:
nginx: [emerg] bind() to 0.0.0.0:1935 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:8080 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:1935 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:8080 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:1935 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:8080 failed (48: Address already in use)
发现前面有尝试过开启,虽然报错了,端口还是被占用了
$ sudo nginx -s stop
顺利开启之后,开始配置hls支持
第四步:配置hls
worker_processes 1;
#error_log logs/error.log debug;
events {
worker_connections 1024;
}
rtmp {
server {
listen 1935;
application zbcs {
live on;
record off;
}
#配置HLS支持开始
application hls {
live on;
hls on;
hls_path /usr/local/var/www/hls;
hls_fragment 5s;
}
#配置HLS支持结束
}
}
http {
server {
listen 8080;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#HLS可在http下访问
location /hls {
# Serve HLS fragments
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
root /usr/local/var/www;
add_header Cache-Control no-cache;
}
#HLS在http结束
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
然后重新load配置文件
$ sudo nginx -s reload
报错:
nginx: [error] open() "/usr/local/var/run/nginx.pid" failed (2: No such file or directory)
需要重新设置一下配置文件:
$ sudo nginx -c /usr/local/etc/nginx/nginx.conf
$ sudo nginx -s reload
$ sudo nginx //开启服务器
还有一种错误:
[emerg] 31225#0: unknown directive "rtmp" in /usr/local/etc/nginx/nginx.conf:9
这是因为rtmp 模块没有加进去,需要重新安装一下:
$ brew uninstall nginx-full// 删除
$ nginxbrew install nginx-full --with-rtmp-module// 安装
终于到了第五步:利用ffmpeg推送流:
$ brew install ffmpeg // 安装ffmpeg
$ ffmpeg -re -i 视频的据对路径 -vcodec copy -acodec copy -f flv rtmp://localhost:1935/hls/movie //指向在/usr/local/var/www 下建立一个可读可写的hls文件夹
结果ts文件虽然是有一直生成,但是不能播放:
$ ffmpeg -re -i 视频的据对路径 -vcodec libx264 -acodec aac -strict -2 -f flv rtmp://127.0.0.1:1935/hls/movie // 搞定
可通过直接访问: