My Music (Listen with quality headphones)

Sunday, 17 February 2013

Linux bash script code to convert wav file into equal wav loops based on in-parameters

Let's say you've recorded a track in LMMS that is composed of 10 measures *of equal length*, at 140 BPM (beats per minute) and you want to convert each measure to its own wav file loop, i.e. 10 individual loop files.


The script below does exactly this.

To use this script in linux:
0) make sure you have installed sox:
sudo apt-get install sox

1) paste the bash script code below into a new file called makeloops.sh and save it somewhere, e.g. ~/Downloads/ (the Downloads folder in your home directory, i.e. /home/me/Downloads)

2) make the bash script file executable:
chmod +x ~/Downloads/makeloops.sh

3) cd to the folder where your wav file (e.g. input.wav) is, e.g.:
cd ~/lmms/projects/your-lmms-project/

4) run makeloops.sh, e.g.:
. ~/Downloads/makeloops.sh input.wav 140 10 1

###### makeloops.sh (START COPYING BELOW THIS LINE) ####

#!/bin/bash

# INPUT PARAMETERS: $1==inputfile name (e.g. input.wav), $2==bpm (e.g. 140), $3==total measures of input file (e.g. 10), $4==loop length measures (e.g. 1), $5==loop folder name (e.g. loops)
#
# e.g. say you have a wav file, input.wav, that contains 10 measures *of equal length* of 140 BPM audio and you want to convert each measure to its own wav file loop:
#
#    SEE "HELP" SECTION FOR EXAMPLE
#

EXPECTED_ARG_COUNT=5

# HELP
# IF NUMBER OF PARAMS < 5, OUTPUT HELP TEXT
if [ $# -ne $EXPECTED_ARG_COUNT ]
then
    echo "";
    echo "USAGE: makeloops.sh input-file-name BPM total-number-of-measures-in-input-file number-of-measures-for-loop-length loop-folder-name";
    echo "";
    echo "EXAMPLE: nickleus@mylaptop:/path/to/input/wav/file/$ . /path/to/makeloops.sh input.wav 140 10 1 loops";
    echo "";

else

LOOPSTART=0;
BPS=$(echo $2/60|bc -l);
BEATS=$(echo 4*$4|bc -l);
LOOPLENGTH=$(echo $BEATS/$BPS | bc -l | awk '{printf("%.7f", $1);}');    # max 7 digits to the right of the decimal place for float numbers, no leading zeros on left side of decimal place

# INPUT ($2) 140    ($3) 10    ($4) 1
#echo $BPS    # 2.33333333333333333333
#echo $BEATS    # 4
#echo $LOOPLENGTH    # 1.7142857

LOOPSFOLDER=$5;
mkdir $LOOPSFOLDER;

for (( w = 0 ; w < $3 ; w++ ));
do
sox -V4 "$1" "./$LOOPSFOLDER/$w.wav" trim $LOOPSTART $LOOPLENGTH;
LOOPSTART=$(echo $LOOPSTART+$LOOPLENGTH|bc -l);
done;

fi


###### (STOP COPYING ABOVE THIS LINE) ####


Note: If you don't want sox to run in full verbose mode, then just remove -V4; but it can be interesting to see what sox is actually doing during conversion.

No comments:

Post a Comment

Post a Comment

My content is under the Creative Commons Attribution 3.0 license. I work hard to publish relevant and useful information in order to help people learn difficult things and find solutions to their problems, so please attribute me if you reuse my content elsewhere.