Skip to content

Instantly share code, notes, and snippets.

@genecyber
Created January 26, 2024 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genecyber/fd2e2622f7028cd83761caf1157810eb to your computer and use it in GitHub Desktop.
Save genecyber/fd2e2622f7028cd83761caf1157810eb to your computer and use it in GitHub Desktop.
Youtube mp3 audio extractor : ./yt-audioClip.py "http://youtube?something" "00:15" "03:00" "extracted.mp3"
#!/bin/bash
youtube_url_or_local_file="https://www.youtube.com/watch?v=nDe8D6h9Vkk"
start_time_m="00:29"
end_time_m="00:32"
output_file_mp3="Italian.mp3"
# Check if 4 arguments are passed (YouTube URL or local file, start time, end time, output file)
if [ "$#" -eq 4 ]; then
# Assign arguments to variables if passed
youtube_url_or_local_file=$1
start_time_m=$2
end_time_m=$3
output_file_mp3=$4
fi
input=$youtube_url_or_local_file
start_time=$start_time_m
end_time=$end_time_m
output_file=$output_file_mp3
# Function to extract YouTube video ID from URL
extract_youtube_id() {
echo "$1" | grep -o 'watch?v=[^&]*' | cut -d'=' -f2
}
# Check if input is a YouTube URL
if [[ $input == http* && $input == *youtube.com* ]]; then
# Extract YouTube video ID
video_id=$(extract_youtube_id "$input")
temp_file="./media/${video_id}.mp4"
# Check if a file with this video ID already exists
if [[ ! -f "$temp_file" ]]; then
echo "Downloading video from YouTube using yt-dlp..."
yt-dlp -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4' -o "$temp_file" "$input"
else
echo "Using existing video file: $temp_file"
fi
else
# It's a local file
echo "Using local file: $input"
temp_file=$input
fi
# Convert times to seconds, ensuring that time values are not empty
start_min=${start_time_m%%:*}
start_sec=${start_time_m##*:}
end_min=${end_time_m%%:*}
end_sec=${end_time_m##*:}
start_seconds=$((start_min * 60 + start_sec))
end_seconds=$((end_min * 60 + end_sec))
duration=$((end_seconds - start_seconds))
# Extract and convert the audio segment to MP3
echo "Extracting audio..."
ffmpeg -i "$temp_file" -ss "$start_seconds" -t "$duration" -vn -acodec libmp3lame "./out/$output_file"
echo "Output saved to ./out/$output_file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment