#!/bin/bash

# record sound output to mp3 file

# requires: pulseaudio-utils, id3v2, sox

# argument: filename
# filename should be in the form "author - title" (with '-' as separator by default)
# if either is unknown, it can be also "author" or "- title"

# output_recorder "The Puzzotronic - Incredible Song" will produce
# The Puzzotronic - Incredible Song.mp3
# tagged with AUTHOR = "The Puzzotronic" and TITLE = "Incredible Song"

# if no argument is given, output file is called record.mp3 and artist is set to username

# feel free to edit parameters if needed

# - - - - - - - - - - - - - - -

MP3_BITRATE=256
OUTPUT_FILENAME="record"

ALSA_DEVICE=`pactl list | grep monitor | grep Name  | awk '{print $2}'`
#ALSA_DEVICE="alsa_output.pci-0000_00_1b.0.analog-stereo.monitor"
CHANNELS=2
SAMPLING_RATE=44100
QUANTIZATION=16

ARTIST=""
TITLE=""
SEPARATOR='-'

# - - - - - - - - - - - - - - -

if [ $# -gt 0 ]
then
	OUTPUT_FILENAME=$1
fi

pacat --record -d $ALSA_DEVICE | sox -t raw -r $SAMPLING_RATE -e signed-integer -L -b $QUANTIZATION -c $CHANNELS - temp.wav &

read -p "Recording, press enter to stop" 

pkill pacat

echo "Normalizing..."

sox --norm temp.wav -C $MP3_BITRATE "$OUTPUT_FILENAME".mp3 silence 1 0 0%
rm temp.wav

echo "Tagging mp3 file..."

OIFS=$IFS
IFS=$SEPARATOR
auttit=($OUTPUT_FILENAME)
IFS=$OIFS

AUTHOR=`echo ${auttit[0]}`
TITLE=`echo ${auttit[1]:1}`

if [ $# -eq 0 ]
then
	AUTHOR=`whoami`
	TITLE=""
fi

echo "Author = $AUTHOR"
echo "Title = $TITLE"

id3v2 -a "$AUTHOR" -t "$TITLE" "$OUTPUT_FILENAME".mp3

echo "Saved on $OUTPUT_FILENAME.mp3"

