Skip to content

Instantly share code, notes, and snippets.

@bemxio
Last active June 25, 2024 14:51
Show Gist options
  • Save bemxio/a16184bad962b9950c2d2fae0aeabc5f to your computer and use it in GitHub Desktop.
Save bemxio/a16184bad962b9950c2d2fae0aeabc5f to your computer and use it in GitHub Desktop.

Bash scripts for broadcasting an HLS audio stream, either from files or your desktop output. Uses ffmpeg, http.server from Python and a tunnel from cloudflared. stream_file.sh requires the path to a file or directory as an argument, stream_loopback.sh needs the input device to be specified in the variable at line 4. Make sure to fill up TUNNEL_UUID (line 7) in either script, in case you want to use tunneling.

#!/bin/bash
# constants
INPUT_PATH="$1"
OUTPUT_PATH="/tmp/stream"
TUNNEL_UUID=""
SERVER_ADDRESS="localhost"
SERVER_PORT="8080"
# create the output directory
mkdir -p "$OUTPUT_PATH"
# start the server and the tunnel
python -m http.server $SERVER_PORT \
--bind $SERVER_ADDRESS \
--directory "$OUTPUT_PATH" &
cloudflared tunnel --loglevel warn run \
--url http://$SERVER_ADDRESS:$SERVER_PORT \
--credentials-file ~/.cloudflared/$TUNNEL_UUID.json \
--protocol http2 \
$TUNNEL_UUID &
# start the stream
if [ -d "$INPUT_PATH" ]; then
shopt -s nullglob nocaseglob
ffmpeg -threads 0 -re -stream_loop -1 \
-f concat -safe 0 -i <(printf "file %q\n" "$INPUT_PATH"/*.{wav,flac,mp3,m4a,ogg} | sort -Vk1) -map 0:a \
-c:a aac -b:a 160k -ac 2 \
-f hls -hls_list_size 10 -hls_time 3 -hls_flags delete_segments "$OUTPUT_PATH"/stream.m3u8
shopt -u nullglob nocaseglob
else
ffmpeg -threads 0 -re -stream_loop -1 \
-i "$INPUT_PATH" -map 0:a \
-c:a aac -b:a 160k -ac 2 \
-f hls -hls_list_size 10 -hls_time 3 -hls_flags delete_segments "$OUTPUT_PATH"/stream.m3u8
fi
# kill the server and the tunnel
pkill -f python
pkill -f cloudflared
# remove the output directory
rm -rf "$OUTPUT_PATH"
#!/bin/bash
# constants
INPUT_DEVICE="alsa_output.pci-0000_00_1f.3.analog-stereo.monitor"
OUTPUT_PATH="/tmp/stream"
TUNNEL_UUID=""
SERVER_ADDRESS="localhost"
SERVER_PORT="8080"
# create the output directory
mkdir -p "$OUTPUT_PATH"
# start the server and the tunnel
python -m http.server $SERVER_PORT \
--bind $SERVER_ADDRESS \
--directory "$OUTPUT_PATH" &
cloudflared tunnel --loglevel warn run \
--url http://$SERVER_ADDRESS:$SERVER_PORT \
--credentials-file ~/.cloudflared/$TUNNEL_UUID.json \
--protocol http2 \
$TUNNEL_UUID &
# start the stream
ffmpeg -threads 0 -re \
-f pulse -i $INPUT_DEVICE \
-c:a aac -b:a 160k -ac 2 \
-f hls -hls_list_size 10 -hls_time 3 -hls_flags delete_segments "$OUTPUT_PATH"/stream.m3u8
# kill the server and the tunnel
pkill -f python
pkill -f cloudflared
# remove the output directory
rm -rf "$OUTPUT_PATH"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment