termux-url-opener bash script for downloading and playing Youtube videos

How I download and play YouTube videos with my smartphone using vlc and yt-dlp! I wrote this bash script as ~/bin/termux-url-opener and tell the YouTube app to share with termux. Prompts if I want to download an mp3 audio or video, saves the file, then opens it ad free in vlc.

#!/bin/bash

read -t 5 -p "Hit m for mp3 otherwise download video: " CHOICE

if [[ "$CHOICE" == "m" ]]; then
        DOWNLOAD_DIR="/sdcard/Movies"                                     
		cd "$DOWNLOAD_DIR"

        FILENAME=$(yt-dlp -x --audio-format mp3 --print filename -o "%(title)s.mp3" "$1")
        FILENAME=${FILENAME%.*}.mp3            
                   
        echo "downloading mp3..." $FILENAME
        yt-dlp "$1" -x --audio-format mp3 -o "$FILENAME"
         
        am start -a android.intent.action.VIEW \                                   -
			 -d "file://$DOWNLOAD_DIR/$FILENAME" \                           
			 -t "audio/mp3" \
             -n org.videolan.vlc/org.videolan.vlc.gui.video.VideoPlayerActivity
        exit 1
fi                                                                                                                                  

DOWNLOAD_DIR="/sdcard/Movies"
cd "$DOWNLOAD_DIR"

FORMAT="bestvideo[height<=240]+bestaudio[abr<=128]/best[height<=240]"
FILENAME=$(yt-dlp -f "$FORMAT" --print filename -o "%(title)s.%(ext)s" "$1")

echo "Downloading: $FILENAME"
yt-dlp -o "%(title)s.%(ext)s" "$1" -f "$FORMAT"

if [ $? -ne 0 ]; then
        echo "Got error, retrying in 10 secomds"
        sleep 10

        yt-dlp -o "%(title)s.%(ext)s" "$1" -f "$FORMAT"
fi

am start -a android.intent.action.VIEW \
         -d "file://$DOWNLOAD_DIR/$FILENAME" \
         -t "video/*" \
         -n org.videolan.vlc/org.videolan.vlc.gui.video.VideoPlayerActivity

Leave a Reply

Your email address will not be published. Required fields are marked *