Guest User

cut audio / video, mp3, flac, etc.

a guest
Jan 18th, 2023
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.12 KB | Music | 0 0
  1. #!/bin/bash
  2.  
  3. function cut_audio_mp3() {
  4.   readarray -t mp3_files < <(find ./ -maxdepth 1 -type f -regex '.*\.\(mp3\|flac\)$' | sed "s/.*\///")
  5.   if [ ${#mp3_files[@]} -eq 1 ]; then
  6.     j=0
  7.     for i in "$@"; do
  8.       ((j++))
  9.       if [ $((j%2)) -eq 0 ]; then
  10.         end_time=$i
  11.         MPHR=60
  12.         IFS=':' read -ra start_array <<< "$start_time"
  13.         IFS=':' read -ra end_array <<< "$end_time"
  14.         len_start_min=${#start_array[0]}
  15.         len_start_sec=$(( $len_start_min + 1 ))
  16.         len_end_min=${#end_array[0]}
  17.         len_end_sec=$(( $len_end_min + 1 ))
  18.         start_time_sec=$(( ( 10#${start_time:0:$len_start_min} ) * MPHR + 10#${start_time:$len_start_sec} ))
  19.         duration=$(( ( 10#${end_time:0:$len_end_min} - 10#${start_time:0:$len_start_min} ) * MPHR + 10#${end_time:$len_end_sec} - 10#${start_time:$len_start_sec} ))
  20.         file_name=$(basename "${mp3_files[0]}" | cut -d. -f1)
  21.         file_extension=$(basename "${mp3_files[0]}" | cut -d. -f2)
  22.         escape=("[" "]" "~" "!" "{" "}" "(" ")" "$" "@" "<" ">" ":" ";" "," '`' "%" "+" "=" '"' "|" "?" '*' "&" " " "'")
  23.         for e in "${escape[@]}"
  24.         do
  25.           file_name=${file_name//[$e]/\\$e}
  26.         done
  27.         file_name=${file_name//"\\'"/"'\"\'\"'"}
  28.         out_name=$(echo $file_name"_"$start_time"-"$end_time"."$file_extension | sed s/:/_/g)
  29.         # removes metadata
  30.         cmd=$(echo ffmpeg -y -ss $start_time_sec -t $duration -i "$file_name"."$file_extension" -map_metadata -1 -c:a copy "$out_name")
  31.         # no metadata removal
  32.         # cmd=$(echo ffmpeg -y -ss $start_time_sec -t $duration -i "$file_name"."$file_extension" -c:a copy "$out_name")
  33.         # echo $cmd
  34.         bash -c "$cmd" &
  35.       else
  36.         start_time=$i
  37.       fi
  38.     done
  39.   else
  40.     echo "error, 2 or more input files detected"
  41.   fi
  42. }
  43.  
  44. cut_audio_mp3 01:00 01:15
  45. # cut_audio_mp3 01:00 01:15 30:01 30:22 60:05 70:10
  46. # dependecies:
  47.   # sudo apt install ffmpeg
  48. # function usage:
  49.   # function name followed by start time, end time, time markers respectively
  50.   # put only 1 mp3 or 1 flac file in the same folder as script file (chmod +x cut_audio_mp3.bash)
Add Comment
Please, Sign In to add comment