如何一键使用树莓派搭建RTMP直播服务

10年前,我写过一篇文章,给大家介绍了一下如何用最低的成本转播PlayStation 4到国内的直播平台。简单来说,就是用PS4自带的直播功能,推流到twitch,并使用树莓派截取信号并重新推送到其他的直播平台。这样做的好处是,不需要购买昂贵的视频采集卡,只需要一个树莓派就可以了。

10年后,我又有了类似的需求,只不过这次,我想做的是自己搭建一个直播服务来输出视频信号,这样,无论我身处何地,都可以通过网络来观看自己的视频。

当然,和10年前不同的,这次我购买了昂贵的视频采集卡,以及新的树莓派。并且,当时我研究了很久如何配置服务器之类的,这次chatgpt帮我一波搞定,并且连脚本都给我写好了。稍微调整一下就能用。所以也在这里分享给大家。这次的思路是,用树莓派搭建一个RTMP服务,然后用我的台式机将视频采集卡采集的内容通过OBS推给树莓派,这样我就可以通过VLS甚至浏览器直接观看内容了。

#!/bin/bash

# Raspberry Pi 5 RTMP Streaming Server Setup Script
# Installs NGINX with RTMP, configures HLS, and sets up systemd service

set -e

echo "🚀 Updating system..."
apt update && apt upgrade -y

echo "📦 Installing dependencies..."
apt install -y build-essential libpcre3 libpcre3-dev libssl-dev zlib1g-dev git wget

echo "🌐 Downloading NGINX and RTMP module..."
cd /opt
git clone https://github.com/arut/nginx-rtmp-module.git
wget http://nginx.org/download/nginx-1.27.5.tar.gz
tar -zxvf nginx-1.27.5.tar.gz
cd nginx-1.27.5

echo "⚙️ Building NGINX with RTMP module..."
./configure --with-http_ssl_module --add-module=../nginx-rtmp-module
make -j$(nproc)
make install

echo "📝 Writing NGINX config with RTMP + HLS..."
cat > /usr/local/nginx/conf/nginx.conf <<EOF
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    sendfile off;
    tcp_nopush on;
    directio 512;

    server {
        listen 8080;

        location / {
            root html;
            index index.html index.htm;
        }

        location /hls {
            types {
                application/vnd.apple.mpegurl m3u8;
                video/mp2t ts;
            }
            root /tmp;
            add_header Cache-Control no-cache;
            add_header 'Access-Control-Allow-Origin' '*';
        }
    }
}

rtmp {
    server {
        listen 1935;
        chunk_size 4096;

        application live {
            live on;
            record off;
            hls on;
            hls_path /tmp/hls;
            hls_fragment 3s;
            hls_playlist_length 60s;
        }
    }
}
EOF

echo "📁 Creating HLS output directory..."
mkdir -p /tmp/hls

echo "🔧 Creating systemd service for NGINX RTMP..."
cat > /etc/systemd/system/nginx-rtmp.service <<EOF
[Unit]
Description=NGINX RTMP Streaming Server
After=network.target

[Service]
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PIDFile=/usr/local/nginx/logs/nginx.pid
Type=forking
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

echo "🔁 Enabling and starting NGINX service..."
systemctl daemon-reexec
systemctl daemon-reload
systemctl enable nginx-rtmp
systemctl start nginx-rtmp

echo ""
echo "✅ All done!"
echo ""
echo "🎥 Set OBS to stream to: rtmp://<RPI_IP_ADDRESS>/live/<key>"
echo "📺 Watch via VLC or player: rtmp://<RPI_IP_ADDRESS>/live/<key>"
echo "🌐 Or in browser (HLS): http://<RPI_IP_ADDRESS>:8080/hls/<key>.m3u8"

记得用sudo run一下就好了……这个脚本会帮你自动下载nginx和rtmp插件,自动编译和安装,自动配置,自动设置自动启动……

欢迎讨论……