Text-to-speech in PHP with Google Translate - php

I am trying to convert words to speech ..
Untill now I have tried this:
<?php
$text = "Hello this is a test for voice api of google";
// Name of the MP3 file generated using the MD5 hash
$file = md5($text);
// Save the MP3 file in this folder with the .mp3 extension
$file = "audio/" . $file .".mp3";
if($file) {
echo "created";
} else {
echo "not created";
}
// If the MP3 file exists, do not create a new request
if (!file_exists($file)) {
$mp3 = file_get_contents(
'http://translate.google.com/translate_tts?q=' . $text);
echo "hello";
file_put_contents($file, $mp3);
} else {
echo "hii";
}
?>
In my html file :
<audio controls="controls" autoplay="autoplay">
<source src="<?php echo $file; ?>" type="audio/mp3" />
</audio>
I am getting created hello and an audio player in output. But no file is played and neither it is created in the folder?

There is a problem with the url you try to access. It is broken ! You should have tried first.
The new URL, that I found on the FF console is :
http://translate.google.com/translate_tts?ie=UTF-8&q=Hello&tl=en&total=1&idx=0&textlen=5&prev=input
For the single word Hello. And you see that you have to specify the language, and the length of your text in textlen, even though it did work for all the sentences I tried without changing this var.
Another problem is that you have to urlencode() your text, or you will have a bug with accents and punctuation.
So the line to download the MP3 becomes :
// Language of the sentence
$lang = "fr";
$mp3 = file_get_contents(
'http://translate.google.com/translate_tts?ie=UTF-8&q='. urlencode($text) .'&tl='. $lang .'&total=1&idx=0&textlen=5&prev=input');
So the complete code looks like :
<?php
$text = "Bonjour, comment allez vous ?";
// Yes French is a beautiful language.
$lang = "fr";
// MP3 filename generated using MD5 hash
// Added things to prevent bug if you want same sentence in two different languages
$file = md5($lang."?".urlencode($text));
// Save MP3 file in folder with .mp3 extension
$file = "audio/" . $file . ".mp3";
// Check folder exists, if not create it, else verify CHMOD
if (!is_dir("audio/"))
mkdir("audio/");
else
if (substr(sprintf('%o', fileperms('audio/')), -4) != "0777")
chmod("audio/", 0777);
// If MP3 file exists do not create new request
if (!file_exists($file))
{
// Download content
$mp3 = file_get_contents(
'http://translate.google.com/translate_tts?ie=UTF-8&q='. urlencode($text) .'&tl='. $lang .'&total=1&idx=0&textlen=5&prev=input');
file_put_contents($file, $mp3);
}
?>

I found it:
https://translate.google.com.vn/translate_tts?ie=UTF-8&client=tw-ob&q=ANYTHING_TEXT&tl=YOUR_LANGUAGE_CODE
Important: client=tw-ob
YOUR_LANGUAGE_CODE can be en,us,uk,vi etc.

An improved version:
// ~~~ Credits to kube ~~~
$text = "Hello this is a test for voice api of google";
$text = urlencode($text);
$lang = urldecode("en");
$file = "audio/" . md5($text) .".mp3";
if (!file_exists($file) || filesize($file) == 0) {
$mp3 = file_get_contents('http://translate.google.com/translate_tts?ie=UTF-8&q='.$text.'&tl='.$lang.'&total=2&idx=0&textlen='.strlen($text).'&prev=input');
if(file_put_contents($file, $mp3)){
echo "Saved<br>";
}else{
echo "Wasn't able to save it !<br>";
}
} else {
echo "Already exist<br>";
}

You cannot use this service for free.
Is there any free quota?
No, the Google Translate API is only available as a paid service. Please see Pricing and Support for more details. However we do offer the Google Website Translator gadget, which will translate your website without charge.
Check translate API FAQ
More info about this unofficial way of use you can find on Techcrunch

You can also use the simple code below. Just echo the code to get the result. In this code, there is no need to save a file or getting permission problems.
echo "<iframe hidden src='http://translate.google.com/translate_tts?ie=UTF-8&q=Welcome%20back%20".$jvm['firstname']."&tl=en&total=2&idx=0&textlen=5&prev=input'></iframe>";

Your file is not creating because you forgot to create it , use below code for creating the file.
$file = "audio/".$file.".mp3";
$ourFileHandle = fopen($file, 'w') or die("can't open file");

Related

PHP save the file using the link found by the block ID on the page

On the page https://data.mos.ru/opendata/61241/ the first url with parameter "export/get?id=" contains the last actual link to download the open data csv file //op.mos.ru/EHDWSREST/catalog/export/get?id=989116 .
The problem is that the digital ending of the url after each update is different and is not known in advance.
I have a script that works and allows me to save a file at a pre-known file url (but it only saves the old version of the file, not the current one):
<?php
function downloadJs($file_url, $save_to)
{
$content = file_get_contents($file_url);
file_put_contents($save_to, $content);
}
downloadJs('https://op.mos.ru/EHDWSREST/catalog/export/get?id=989116', realpath("./img/feeds") . '/61241.zip');
$zip = new ZipArchive;$zip->open('./img/feeds/61241.zip');$zip->extractTo('./img/feeds/61241');$zip->close();
$directory = './img/feeds/61241/'; if ($handle = opendir($directory)) { while (false !== ($fileName = readdir($handle))) { $dd = explode($fileName); $newfile = '61241.csv'; rename($directory . $fileName, $directory.$newfile); } closedir($handle); }
echo "Ok!";
?>
I need to change this PHP script so that on the page https://data.mos.ru/opendata/61241/ first determined the first link to the download file by the parameter "export/get?id=", where the link is located.
I'm not sure if you understand what you mean.
we have:
<a target="_blank" href="//op.mos.ru/EHDWSREST/catalog/export/get?id=989116" onclick="yaCounter29850344.reachGoal('download_csv')...
Perhaps we will use a little regex to get that id.
Let's say you already have its html with file_get_contents:
preg_match('#get\?id=(\d+)".* onclick="[^"]+csv[^"]+"#', $html, $matches);
echo $matches[1]; // 989116

Unable to copy image from URL in PHP with upload class

I'm trying to make a upload class with PHP. so this is my first PHP class:
//Create Class
class Upload{
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
if(copy($Content, '/test/sdfsdfd.jpg')){
return "UPLOADED";
}else{
return "ERROR";
}
}
}
and usage:
$Upload = new Upload();
echo $Upload->Remote('https://www.gstatic.com/webp/gallery/4.sm.jpg');
problem is, this class is not working. where is the problem? I'm new with PHP classes and trying to learn it.
thank you.
copy expects filesystem paths, e.g.
copy('/path/to/source', '/path/to/destination');
You're passing in the literal image you fetched, so it's going to be
copy('massive pile of binary garbage that will be treated as a filename', '/path/to/destination');
You want
file_put_contents('/test/sdfsdfg.jpg', $Content);
instead.
PHP's copy() function is used for copying files that you have permission to copy.
Since you're getting the contents of the file first, you could use fwrite().
<?php
//Remote Image Upload
function Remote($Image){
$Content = file_get_contents($Image);
// Create the file
if (!$fp = fopen('img.png', 'w')) {
echo "Failed to create image file.";
}
// Add the contents
if (fwrite($fp, $Content) === false) {
echo "Failed to write image file contents.";
}
fclose($fp);
}
Since you want to download a image, you could also use the imagejpeg-method of php to ensure you do not end up with any corrupted file format afterwards (http://de2.php.net/manual/en/function.imagejpeg.php):
download the target as "String"
create a image resource out of it.
save it as jpeg, using the proper method:
inside your method:
$content = file_get_contents($Image);
$img = imagecreatefromstring($content);
return imagejpeg($img, "Path/to/targetFile");
In order to have file_get_contents working correctly you need to ensure that allow_url_fopen is set to 1 in your php ini: http://php.net/manual/en/filesystem.configuration.php
Most managed hosters disable this by default. Either contact the support therefore or if they will not enable allow_url_fopen, you need to use another attempt, for example using cURL for file download. http://php.net/manual/en/book.curl.php
U can use the following snippet to check whether its enabled or not:
if ( ini_get('allow_url_fopen') ) {
echo "Enabled";
} else{
echo "Disabled";
}
What you describe is more download (to the server) then upload. stream_copy_to_stream.
class Remote
{
public static function download($in, $out)
{
$src = fopen($in, "r");
if (!$src) {
return 0;
}
$dest = fopen($out, "w");
if (!$dest) {
return 0;
}
$bytes = stream_copy_to_stream($src, $dest);
fclose($src); fclose($dest);
return $bytes;
}
}
$remote = 'https://www.gstatic.com/webp/gallery/4.sm.jpg';
$local = __DIR__ . '/test/sdfsdfd.jpg';
echo (Remote::download($remote, $local) > 0 ? "OK" : "ERROR");

the filename .xls is not readable

I want to download file .xls and then upload it to database oracle. but I am getting an error "the filename .xls is not readable".
Below is my script:
<? require_once (dirname(__FILE__)."/upload/upBc.php");
if(!empty($_FILES["file"])){
echo $file = $_FILES["file"];
}else{
/*$file = "/opt/lampp/htdocs/avar/pp/ccr/test.xls";*/
$file = '/www.upload.com/pm_ms/test.xls';
/* $file = "website_data_". date('ymd').".xls";*/
}
$upload = new upload();
$upload->setFile($file);
$upload->getFileType();
$upload->getFileName();
$upload->getFileDir();
$upload->readDataTbc();
$dataD = array ();
$dataD = $upload->getDataTbc();
echo "<table border = 1>";
for($i=1;$i < count($dataD);$i++){
echo "<tr>";
for($j=0;$j < $upload->getHSize();$j++){
echo " <td>".$dataD[$i][$j]."</td>";
}
echo"</tr>";
}
echo"</table>";
echo"data length=". count($dataD);
$upload->commitDataTbc();
?>
If I use $file = "/opt/lampp/htdocs/avar/pp/ccr/test.xls";. in my program it works
but if I use $file = '/www.upload.com/pm_ms/test.xls';. I get the error THE FILENAME test.xls is Not Readable
That's probably because /www.upload.com/ doesn't exist on your server.
Do you know the actual path to the file? By prefixing the URI with / this makes it absolute, which means that it's trying to read literally from /www.upload.com on your server. If you're looking to make this relative you could try ./upload.com/ or simply upload.com/ as the path prefix.
If you are however trying to load it from the website upload.com (instead of a folder from your server) you have two options:
(If Supported) Set the filename as a URL ie. $file = 'http://www.upload.com/pm_ms/test.xls';
Download the file and then open it locally.
For #2:
$file = 'test.xls';
$ctnts = file_get_contents('http://www.upload.com/pm_ms/test.xls');
file_put_contents($file, $ctnts);

PHP Extract only the Filename from UNC Path

I'm trying to create an Intranet page that looks up all pdf documents in a UNC path and the returns them in a list as hyperlinks that opens in a new window. I'm nearly there however the following code displays the FULL UNC path - My question how can I display only the Filename (preferably without the .pdf extension too). I've experimented with the basename function but can't seem to get the right result.
//path to Network Share
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>$file</a><br>";
}
The links work fine it just the display text shows //myserver/adirectory/personnel/document.pdf rather than just document. Note the above code was taken from another example I found whilst researching. If there's a whole new better way then I'm open to suggestions.
echo basename($file);
http://php.net/basename
Modify your code like this:
<?
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>".basename($file)."</a><br>";
}
?>
You may try this, if basename() does not work for some reason:
$file_a = explode('/',$file);
if (trim(end($file_a)) == '')
$filename = $file_a[count($file_a)-2];
else
$filename = end($file_a);

How to auto delete a zip file after using stream_get_contents(); to view a file in php?

I have this code to read a file for preview, but the downside is I have to download the file first from cloud and read from it, but it's a waste of space so I want to delete it after viewing a certain file. Is there an automatic way of doing this? Or do I have to integrate it to a close button?
// Get the container we want to use
$container = $conn->get_container('mailtemplate');
//$filename = 'template1.zip';
// upload file to Rackspace
$object = $container->get_object($filename);
//var_dump($object);
//echo '<pre>' . print_r($object,true) . '</pre>';
$localfile = $dir.$filename;
//echo $localfile;
$object->save_to_filename($localfile);
if($_GET['preview'] == "true")
{
$dir = "../mailtemplates/";
$file1 = $_GET['tfilename'];
$file = $dir.$file1;
$file2 = "index.html";
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
$path = $file_name.'/'.$file2;
$zip = new ZipArchive();
$zip->open($file);
$fp = $zip->getStream($path);
if(!$fp)
{
exit("faileds\n");
$zip->close();
unlink($dir.$filename);
}
else
{
$stuff = stream_get_contents($fp);
echo $stuff;
$zip->close();
if($stuff != null)
{
unlink($dir.$filename);
}
}
}
else
{
unlink($dir.$filename);
}
You didn't google this did ya?
Try Unlink
Edit:
Taking a look at this code, $zip->open($file); <-- is where you open the file. The file variable is set by:
"../mailtemplates/" . basename($_GET['tfilename'], '.' . $info['extension']) . '/' . "index.html"
So you're grabbing a relative directory and grabbing a filename as a folder, and going to that folder /index.html. Here's an example:
if you're in c:\ testing and you go to ../mailtemplates/ you'll be in c:\mailtemplates and then you're looking at file test.php but you're removing the file extension, so you'll be opening the location c:\mailtemplates\test\index.html so you open up that html file and read it. Then, you're trying to delete c:\mailtemplates\test.php
can you explain how any of that makes sense to you? 'cause that seems very odd to me.

Categories