php - 使用 Google Translate 在 PHP 中进行文字转语音

标签 php html text-to-speech speech google-text-to-speech

我正在尝试将单词转换为语音 ..

到目前为止,我已经试过了:

<?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";
   }
?>

在我的 html 文件中:

<audio controls="controls" autoplay="autoplay">
  <source src="<?php echo $file; ?>" type="audio/mp3" />
</audio>

我在输出中创建了 hello 和音频播放器。但是没有播放文件,也没有在文件夹中创建文件?

最佳答案

  1. 您尝试访问的 URL 有问题。它被打破 !你应该先尝试一下。 我在 FF 控制台上找到的新 URL 是:

    http://translate.google.com/translate_tts?ie=UTF-8&q=Hello&tl=en&total=1&idx=0&textlen=5&prev=input

    对于单个词 Hello。你看到你必须在 textlen 中指定语言和文本的长度,即使它对我在不更改此 var 的情况下尝试的所有句子都有效。

  2. 另一个问题是您必须对您的文本进行 urlencode(),否则您将遇到重音符号和标点符号的错误。 所以下载 MP3 的行变成:

    // 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');
    

所以完整的代码如下:

<?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);
    }

?>

关于php - 使用 Google Translate 在 PHP 中进行文字转语音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14723973/

相关文章:

python - 如何在Pygame中检查混音器系统是否已初始化?

javascript - 在 chrome.tts.speak 中回调?

c# - 将 NAudio 与 SpeechSynthesizer 结合使用

php - 从 PHP 执行 root 命令...有安全的方法吗?

php - 如何表示文件上传的时基进度条

php - 如何将二维 PHP 数组编码为 Javascript 数组?

html - ng-model 不适用于文件输入

php - 这会让搜索引擎为我的内容编制索引吗?

android - 不同移动设备屏幕上游戏的纵横比

php - 获取 json 数组的正确形式语法和相关 jquery 是什么