#!/bin/bash

cd audio
# Create a text file
echo "Filename,Length,Start,End" > output.txt

# Initialize start time
start=0

# Create a list of files to be merged
> files.txt

# Loop over all audio files in the current directory
for file in *.wav; do
  # Get the length of the audio file in seconds with millisecond precision
  length=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file")
  
  # Calculate end time
  end=$(echo "$start + $length" | bc)

  # Write to the file
  echo "$file,$length,$start,$end" >> output.txt

  # Update start time for the next file
  start=$end

  # Add file to the list of files to be merged
  echo "file '$PWD/$file'" >> files.txt
done


# Merge the audio files into a .wav file
ffmpeg -f concat -safe 0 -i files.txt -c copy output.wav

# Convert the .wav file to .mp3
ffmpeg -i output.wav -codec:a libmp3lame -qscale:a 2 output.mp3

# Remove the temporary files
rm files.txt output.wav
# Remove the temporary file
rm files.txt

# Create a Howler.js sprite
echo "var sprite = {" > sprite.js
while IFS=, read -r file length start end
do
  # Convert times to milliseconds
  start_ms=$(echo "$start * 1000" | bc)
  length_ms=$(echo "$length * 1000" | bc)
  #no spaces betweek equal signs bash problems
  base_file=$(basename "$file" .wav)
  echo "  ${base_file}_wav: [$start_ms, $length_ms]," >> sprite.js
done < output.txt
echo "};" >> sprite.js
