Skip to content

Instantly share code, notes, and snippets.

@teklynk
Created October 28, 2025 18:25
Show Gist options
  • Select an option

  • Save teklynk/32bf08b116f404e506ba9a8f5a612509 to your computer and use it in GitHub Desktop.

Select an option

Save teklynk/32bf08b116f404e506ba9a8f5a612509 to your computer and use it in GitHub Desktop.
Record live streams using FFMPEG and the m3u8 url of the stream
#!/bin/bash
# Dependencies
# YT-DLP (YouTube Downloader)
# sudo wget https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -O /usr/local/bin/yt-dlp
# sudo chmod a+rx /usr/local/bin/yt-dlp
# ffmpeg: Install via apt (apt install ffmpeg)
# mpv: Install via apt (apt install mpv)
# Example: ./stream_record.sh -mpv https://listen.batstationrad.io/hls/1/stream.m3u8
# Check if the required yt-dlp package is installed
command -v /usr/local/bin/yt-dlp >/dev/null 2>&1 || { echo "Error: yt-dlp is not installed. Please install it using your package manager." >&2; exit 1; }
# Function to display usage
usage() {
echo "Usage: $0 [-mpv] [-o output_directory] <stream_url>"
echo ""
echo "Options:"
echo " -mpv Play and record the stream using mpv player"
echo " -norecord Play stream but do not record"
echo " -o output_directory Set the output directory (default: ~/Videos)"
exit 1
}
# Default output directory
OUTPUT_DIR="$HOME/Videos"
# Check if at least one argument is provided
if [ $# -lt 1 ]; then
usage
fi
# Parse arguments
MPV_MODE=false
NO_RECORD=false
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-mpv)
MPV_MODE=true
shift
;;
-norecord)
NO_RECORD=true
shift
;;
-o)
OUTPUT_DIR="$2"
shift 2
;;
*)
STREAM_URL="$1"
shift
;;
esac
done
# Check if URL is provided
if [ -z "$STREAM_URL" ]; then
usage
fi
# Create the output directory if it doesn't exist
mkdir -p "$OUTPUT_DIR" || { echo "Failed to create output directory: $OUTPUT_DIR"; exit 1; }
# Change to the output directory
cd "$OUTPUT_DIR" || { echo "Failed to change directory to $OUTPUT_DIR"; exit 1; }
# Define variables
CURRENTDATETIME=$(date '+%F_%H-%M-%S')
FILENAME="stream-$CURRENTDATETIME.ts"
# Determine the recording mode
if $MPV_MODE && ! $NO_RECORD; then
# Play and record the stream using yt-dlp, tee, and ffmpeg
yt-dlp -o - "$STREAM_URL" | tee >(ffmpeg -i - -c copy "$FILENAME") | mpv -
elif $MPV_MODE && $NO_RECORD; then
# Play the stream using yt-dlp and mpv
yt-dlp -o - "$STREAM_URL" | mpv -
else
# Record the stream using yt-dlp and ffmpeg. No video player
yt-dlp -o - "$STREAM_URL" | ffmpeg -i - -c copy "$FILENAME"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment