-accumulated_duration=0
-for file in "${sorted_files[@]}"; do
- duration="${file_durations["$file"]}"
- new_accumulated_duration=$(echo "$accumulated_duration + $duration" | bc)
- if (( $(echo "$random_point < $new_accumulated_duration" | bc -l) )); then
- offset=$(echo "$random_point - $accumulated_duration" | bc)
- yell "Starting playback from $offset seconds into file: $file"
-
- # Create a playlist file
- playlist_file=$(mktemp)
- printf '%s\n' "${sorted_files[@]}" > "$playlist_file"
+accumulated_duration=0;
+accumulated_duration_int=0;
+
+for idx in "${!sorted_files[@]}"; do
+ file="${sorted_files[$idx]}";
+ duration="${file_durations["$file"]}";
+ declare -p idx file duration accumulated_duration 1>&2; # Debugging statement
+
+ # Validate the duration
+ if [[ -n "$duration" && "$duration" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
+ new_accumulated_duration=$(echo "$accumulated_duration + $duration" | bc)
+ # Convert accumulated durations to integers for comparison
+ accumulated_duration_int=$(printf "%.0f" "$accumulated_duration")
+ new_accumulated_duration_int=$(printf "%.0f" "$new_accumulated_duration")
+ else
+ yell "WARNING: Invalid duration '$duration' for file '$file', skipping." 1>&2
+ continue
+ fi
+
+ if (( random_point < new_accumulated_duration_int )); then
+ offset=$(echo "$random_point - $accumulated_duration_int" | bc; );
+ yell "Starting playback from $offset seconds into file: $file";
+
+ # Create an EDL file
+ edl_file=$(mktemp);
+ yell "DEBUG:EDL file at:${edl_file}"; # debug
+ echo "# mpv EDL v0" > "$edl_file";
+
+ # Add first file to start playback at random offset position
+ file_bc="$(prepend_path_bc "$file")"; # See https://github.com/mpv-player/mpv/blob/master/DOCS/edl-mpv.rst#syntax-of-mpv-edl-files
+ printf '%s,%s\n' "$file_bc" "$offset" >> "$edl_file";
+
+ # Append the rest of the files
+ declare -p file offset idx sorted_files edl_file 1>&2; # debug
+ for (( i=idx+1; i<${#sorted_files[@]}; i++ )); do
+ next_file="${sorted_files[$i]}";
+ next_file_bc="$(prepend_path_bc "$next_file")";
+ yell "STATUS:Adding:$next_file";
+ printf '%s\n' "$next_file_bc" >> "$edl_file";
+ done;