#!/usr/bin/php
<?php

ini_set("auto_detect_line_endings", true);

$connector = "watson";
$fileformat = "txt";

$linenumber = 0;

if (count($argv) < 6 || count($argv) > 6) {
	echo help();
} else {
	$count = 1;
	$date = date('His_dny');
	
	//read de file with the text
	$file = fopen($argv[4],"r");
	while(!feof($file)) {
		
    if ($fileformat == "vtt")
		{
    $text = fgets($file);
    $text = str_replace("\n", '', $text); // remove new lines
    $text = str_replace("\r", '', $text); // remove new lines
    $destination = $argv[5].'/'.$text.'.'.'raw';
    $text = fgets($file);
		$text = fgets($file); // duration
		}
    else
    $text = fgets($file);

    if ($text == "\n")
    continue;
    
   	echo "\nLIGNE :\n".$text;    

    if ($text[0] == ';')
    continue;

    if ($fileformat == "txt")    
    $pos = strpos($text, ':');
    else
    $pos = false;
    if ($pos)
    {
   		echo "\nPrompt: avec :\n";
      $destination = substr($text, 0, $pos);

      $file_parts = pathinfo($destination);

      if (isset($file_parts['extension']))
      $format = $file_parts['extension'];
      else
      $format = "raw";

      if (isset($file_parts['dirname']) && $file_parts['dirname'] != "")
      if (!file_exists($file_parts['dirname']))
      mkdir($file_parts['dirname']);

      if (isset($file_parts['extension']))
      $destination = $argv[5].'/'.$destination;
      else
      $destination = $argv[5].'/'.$destination.'.'.$format;

      $text = substr($text, $pos+1);
    }
    else
    {
   		echo "\nPrompt: sans :\n";
      
      $linenumber++;
      $format = "raw";  
      $destination = $argv[5].'/'.$linenumber.'.'.$format;
    }
    //if (!$destination)
    //$destination = false;
		
		$text = rtrim($text);
		echo "\nPrompt: $text\n";
    
    
    if ($connector == 'watson')
    {
      $apikey = "?";
      $apikey= "26SMkTvKPXE9b3rd2GCpzcIbYSTryKt-DEy_VycvbWDf";
  		$url = $argv[1];
      $url = "https://api.eu-de.text-to-speech.watson.cloud.ibm.com/instances/8f036a30-cae4-454b-9471-9a521d54760c/v1/synthesize";
      $voice = "de-DE_ErikaV3Voice";
      $language = "de-DE";
      $format = "audio/mulaw;rate=8000";
      $format = "audio/wav;rate=8000";      
    
  		//set the POST variables
  		//$url = $argv[1];
  		$post = array(
  				'text' => $text,
  				'language' => $language,
  				'voice' => $voice,
          'format' => $format,
  		);
      
      $text_json = json_encode($post);
  		
  		//url-ify the data for the POST
  		$post_string = "";
  		foreach($post as $key=>$value) { $post_string .= $key.'='.$value.'&'; }
  		rtrim($post_string,'&');
  		
  		//open connection
  		$ch = curl_init();
  		
      curl_setopt($ch, CURLOPT_URL, $url.'?voice='.$voice);
      curl_setopt($ch, CURLOPT_HEADER, false);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_USERPWD, 'apikey:' . $apikey);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
          'Content-Type: application/json',
          'Accept: ' . $format,
      ]);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $text_json);
      
      echo "\nDestination: $destination\n";
      
      //$fh = fopen($destination, 'w');      
      //curl_setopt($ch, CURLOPT_FILE, $fh);
       		
  		//execute post
  		$result = curl_exec($ch);
  		
  		//close connection
  		curl_close($ch);
      //fclose($fh);
    }
    else
    {	
  		//set the POST variables
  		$url = $argv[1];
  		$post = array(
  				'text' => $text,
  				'language' => $argv[2],
  				'voice' => $argv[3],
          'format' => $format,
  		);
  		
  		//url-ify the data for the POST
  		$post_string = "";
  		foreach($post as $key=>$value) { $post_string .= $key.'='.$value.'&'; }
  		rtrim($post_string,'&');
  		
  		//open connection
  		$ch = curl_init();
  		
  		//set the url, number of POST vars, POST data
  		curl_setopt($ch, CURLOPT_URL, $url);
  		curl_setopt($ch, CURLOPT_POST, count($post));
  		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
  		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
  		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  		
  		//execute post
  		$result = curl_exec($ch);
  		
  		//close connection
  		curl_close($ch);
    }
		
		//write the file
    if (!$destination)
		$destination = $argv[5]."/sound_line_".$count++."_".$date.".".$format;
		$soundfile = fopen($destination,"wb");
		fwrite($soundfile,$result);
		
		echo "      -> $destination\n";
		
	}	
	echo "\n";
	
}



function help() {
	
	$msg = "This script must be called with the following arguments:\n";
	$msg = $msg."\targ1 - url of the tts generator\n";
	$msg = $msg."\targ2 - language (en es fr ...)\n";
	$msg = $msg."\targ3 - voice of the tts server\n";
	$msg = $msg."\targ4 - path to the file containing the text to convert. ONE MESSAGE PER LINE\n";
	$msg = $msg."\targ5 - path to the folder where the sounds will be stored\n";
	$msg = $msg."Example: php vxmlaudios.php http://myserver/tts/mytttsserver/tts.php en voice1 /path_to_file/texts.txt /path_to_folder/folder\n";
		
	return $msg;
	
}
?>
