#! /usr/bin/perl
use File::Basename;

# Accepts one argument: the full path to a directory.
# Returns: A list of files that end in '.wav'  -- in all subdirectories!
# one channel sound files only
# things that could be done to this script: 
#    process two command line parameters:  root directory for operation, 
#             and target sample rate for output wav files

# recursively decend directory structure getting a list of 
#   all wav files
sub get_wavs {
    my $path    = shift;

    opendir (DIR, $path)
        or die "Unable to open $path: $!";

    my @files =
        map { $path . '/' . $_ }
    grep { !/^\.{1,2}$/ }
    readdir (DIR);

    return
        grep { (/\.wav$/) && (! -l $_) }
    map { -d $_ ? get_wavs ($_) : $_ }
    @files;
}

@files = get_wavs("/home/kjohnson/A_Course_in_Phonetics");

foreach $file (@files) {
    $wav = $file;

    # make the mp3 file name
    ($name,$path,$suffix) = fileparse($wav,".wav");
    $mp3 = "$path$name.mp3";
    next if (-e $mp3);

    # force all sound files to be mono, 16kHz, and normalize amplitude
    $sf = 16000;
    $info = system("sox \"$wav\" temp.wav channels 1 rate $sf norm -3");
    $info = system("mv temp.wav $wav");  # replace sound file
    $info = system("lame --preset voice '$wav' '$mp3'");

}
