run exec() command as many times as the lines of txt file

189 views Asked by At

i'm using Sox (Sound eXchange) library to convert .wav file into .flac. If i use the terminal, it works good:

$Brus:~ pum$ sox outputFolder/file/file.000.wav flac/file.000.flac

and the file file.000.flac was converted into the flac folder rightly.

Also inside my script, if i run:

         exec('sox/sox outputFolder/file/file.000.wav flac/file.000.flac');

the conversion works good.

My problem now, is that i need to convert a batch of file. I create a txt file with the list of files .wav (listWav.txt) to be converted, and i want to run the "exec()" command as many time as there are lines with the file name in the "listWav.txt" file.

This is the listWav.txt file:

outputFiles/file/file.000.wav
outputFiles/file/file.001.wav

This is the listFlac.txt file:

file.000.flac
file.001.flac

This is the code i wrote trying to run "exec()" command as described:

//read all txt files content
$file2 = fopen("listFlac.txt","r");
$file3 = fopen("listWav.txt", "r");
//loop the file and read it line by line
while(! feof($file2) && ! feof($file3)){
  $tt = fgets($file2);
  $tt2 = fgets($file3);
  //run sox conversion
  exec('sox/sox' . ' ' . $tt2 . ' ' . 'flac/' . $tt);
}
fclose($file2);
fclose($file3);

If i print_r('sox/sox' . ' ' . $tt2 . ' ' . 'flac/' . $tt); this is the result:

sox/sox outputFiles/file/file.000.wav flac/file.000.flac sox/sox outputFiles/file/file.001.wav flac/file.001.flac

so the loop of the "exec()" command was executed as many times as the lines of the file "listWav.txt", but it doesn't work properly because only "file.001.flac" was generated, so i understand that the while loop allow "exec()" to take only the end line of the "listWav.txt" file, and run it.

Does anybody know what i have to edit in my script to run "exec()" the number of times for all the files in the list?

EDIT: I solved in this way, i splitted the while in two while nested and called two equivalent "exec()" command. The code could be not elegant but it works for my purpose.

while(! feof($file2)){
  $tt = fgets($file2);
    while (!feof($file3)) {
      $tt2 = fgets($file3);
      exec('sox/sox' . ' ' . $tt2 . ' ' . 'flac/' . $tt);  
    }
      exec('sox/sox' . ' ' . $tt2 . ' ' . 'flac/' . $tt); 
}
1

There are 1 answers

1
vaso123 On

use file function instead, and add a counter to your loop.

$flacArray = file("listFlac.txt");
$wawArray = file("listWav.txt");
$i=0;
foreach ($flacArray as $flac) {
    $wavInfo = pathinfo($wawArray[$i]);
    exec('sox/sox' . ' ' . $flac . ' ' . 'flac/' .  $wavInfo["basename"] . str_pad($i, 3, "0", STR_PAD_LEFT) .".wav");
    $i++;
}

NOTE: This is works only for 999 file.