#!/bin/bash
# Generate sine waves and then combine them to produce signal
# Uses sox as easy to use on command line. Optionally audacity can
# then be used to look at plots of the signals including frequency
# spectrum.
# Demonstrates basic concept of combining sinusoids to create
# digital sqare wave
# Usage:
# generate-sine-signal components fundamental duration
#   components: integer > 1 indicating number of sine components
#   fundamental: fundamental frequency in Hz
#   duration: duration of signal in seconds
# Steven Gordon

# Input parameters
components=$1
fundamental=$2
duration=$3

# Start of names for output files
sine="sine"
signal="signal"

# Precision for calculations
bcscale=5

# Command to combine the sine waves
soxsignal="sox --combine mix"
extraname=""

# For each component generate a sine wave and add to list to combine
for i in `seq 1 ${components}`
do 
	# n, i.e. 1, 3, 5, ...
	n=`echo "scale=${bcscale}; ${i} * 2 - 1" | bc `

	# Frequency of the component
	frequency=`echo "scale=${bcscale}; ${n} * ${fundamental}" | bc`

	# Amplitude of the component
	a=`echo "scale=${bcscale}; 1 / ${n}" | bc`

	# Generate the sine wave with sox
	sox --null ${sine}-${frequency}.wav synth ${duration} sine ${frequency}

	# Mix with other sine waves
	soxsignal="${soxsignal} --volume ${a} ${sine}-${frequency}.wav"
	extraname="${extraname}-${frequency}"
done

# Generate the signal with sox
${soxsignal} ${signal}-${components}-${fundamental}.wav


