通过google语音翻译把给定的文本生成音频文件

星瑶吖_5979

星瑶吖_5979

2016-05-25

2253人浏览

原创

  1. 音频demo

<?php //mp3格式
echo "http://www.codepearl.com/files/212.html";

2.demo

<?php /**
 * http://www.codepearl.com
 */
 
include 'PHP_Text2Speech.class.php';
 
$t2s = new PHP_Text2Speech;
 
?><audio>
  <source>speak('代码珠玑 , 提供编程中 需要的各种工具类 , 算法 , 函数 , 解决方案 , 技术文档 , 致力于做您最好的代码 , 分享平台',"zh-CN"); ?>" type="audio/mp3" />
</source></audio>

3.操作类

JenMusic
JenMusic

JenMusic是一款强调授权训练和高保真输出的 AI 音乐生成平台。

下载
<?php //http://www.codepearl.com
/******************************************************************
Example:
<?php 
$t2s = new PHP_Text2Speech;
?>
  
// Simple example
<audio>
  <source>speak('www.codepearl.com','en'); ?>" type="audio/mp3" />
</source></audio>
  
// Example use of other language
<audio>
  <source>speak('代码珠玑', 'zh-CN'); ?>" type="audio/mp3" />
</source></audio>
  
******************************************************************/
  
class PHP_Text2Speech {
      
    /** Max text characters
     * @var Integer 
     */
    var $maxStrLen = 100;
      
    /** Text len
     * @var Integer 
     */
    var $textLen = 0;
      
    /** No of words
     * @var Integer 
     */
    var $wordCount = 0;
      
    /** Language of text (ISO 639-1)
     * @var String 
     * @link https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
     */
    var $lang = 'en';
      
    /** Text to speak
     * @var String 
     */
    var $text = NULL;
      
    /** File name format
     * @var String 
     */
    var $mp3File = "%s.mp3";
      
    /** Directory to store audio file
     * @var String 
     */
    var $audioDir = "audio/";
      
    /** Contents
    * @var  String
    */
    var $contents = NULL;
      
    /** Function make request to Google translate, download file and returns audio file path
     * @param   String  $text       - Text to speak
     * @param   String  $lang       - Language of text (ISO 639-1)
     * @return  String  - mp3 file path
     * @link https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
     */
    function speak($text, $lang = NULL) {
          
        if ($lang !== NULL) {
            $this->lang = $lang;
        }
          
        // Create dir if not exists
        if (!is_dir($this->audioDir)) {
            mkdir($this->audioDir, 0755) or die('Could not create audio dir: ' . $this->audioDir);
        }
          
        // Try to set writing permissions for audio dir.
        if (!is_writable($this->audioDir)) { 
            chmod($this->audioDir, 0755) or die('Could not set appropriate permissions for audio dir: ' . $this->audioDir);
        }
          
        // Can not handle more than 100 characters so split text
        if (strlen($text) > $this->maxStrLen) {
            $this->text = $text;
              
            // Generate unique mp3 file name
            $file = sprintf($this->mp3File, $this->audioDir . md5($this->text));
            if (!file_exists($file)) {
                $texts = array();
                $words = explode(' ', $this->text);
                $i = 0;
                $texts[$i] = NULL;
                foreach ($words as $w) {
                    $w = trim($w);
                    if (strlen($texts[$i] . ' ' . $w) maxStrLen) {
                        $texts[$i] = $texts[$i] . ' ' . $w; 
                    } else {
                        $texts[++$i] = $w;
                    }
                }
                  
                // Get get separated files contents and marge them into one
                foreach ($texts as $txt) {
                    $pFile = $this->speak($txt, $this->lang);
                    $this->contents .= $this->stripTags(file_get_contents($pFile));
                    unlink($pFile);
                }
                unset($words, $texts);
                  
                // Save file
                file_put_contents($file, $this->contents);
                $this->contents = NULL;
            }
        } else {
              
            // Generate unique mp3 file name
            $file = sprintf($this->mp3File, $this->audioDir . md5($text));
              
            if (!file_exists($file)) {
                // Text lenght
                $this->textLen = strlen($text);
                  
                // Words count
                $this->wordCount = str_word_count($text);
                  
                // Encode string
                $text = urlencode($text);
  
                // Download new file
                $this->download("http://translate.google.com/translate_tts?ie=UTF-8&q={$text}&tl={$this->lang}&total={$this->wordCount}&idx=0&textlen={$this->textLen}", $file);
            }
        }
          
        // Returns mp3 file path
        return $file;
    }
      
    /** Function to find the beginning of the mp3 file
     * @param   String  $contents       - File contents
     * @return  Integer
     */
    function getStart($contents) {
        for($i=0; $i getStart($contents);
        if ($start === FALSE) {
            return FALSE;
        } else {
            return substr($contents, $start);
        }
        // Remove end tag
        if ($this->getEnd($contents) !== FALSE){
            return substr($contents, 0, (strlen($contents) - 129));
        }
    }
      
    /** Function to download and save file
     * @param   String  $url        - URL
     * @param   String  $path       - Local path
     */
    function download($url, $path) { 
        // Is curl installed?
        if (!function_exists('curl_init')){ // use file get contents 
            $output = file_get_contents($url); 
        }else{ // use curl 
            $ch = curl_init(); 
            curl_setopt($ch, CURLOPT_URL, $url); 
            curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1"); 
            curl_setopt($ch, CURLOPT_HEADER, 0); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
            curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
            $output = curl_exec($ch); 
            curl_close($ch); 
        }
        // Save file
        file_put_contents($path, $output);
    }
}

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

语音翻译

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Navicat创建数据库教程
Navicat创建数据库教程

本专题整理Navicat创建数据库相关教程,介绍新建前的准备、基础设置和创建后的检查方法。内容兼顾入门学习及实际使用需求,帮助用户了解不同数据库类型下的操作差异,为后续建表、保存数据和日常管理提供参考。

2026.11.20

0

7

Navicat入门教程大全
Navicat入门教程大全

本专题整理Navicat入门教程,从认识软件界面到开展数据库操作,介绍初次使用需要了解的知识和方法。内容兼顾连接配置、数据管理及日常使用中的疑问,方便用户按学习进度查阅,为后续实践和独立操作打好基础。

2026.11.20

0

17

Navicat数据库连接配置指南
Navicat数据库连接配置指南

从确认数据库信息到建立可用连接,本专题串联Navicat连接数据库的相关知识和操作方法。既有初次配置时需要了解的基础内容,也有连接后的检查思路,方便用户按实际需求查阅教程,逐步熟悉数据库连接的设置流程。

2026.11.20

0

10

PHP8.6数组与数据处理教程
PHP8.6数组与数据处理教程

本专题汇总PHP8.6数组与数据处理教程,涵盖CSV读取和导出、引用遍历删除、array_filter回调模式、配置键名冲突、pathinfo文件名校验、GMP大整数进制转换及UTF-8正则筛选,说明升级兼容变化、输入范围和失败处理方法。

2026.11.20

0

8

PHP8.6升级迁移教程
PHP8.6升级迁移教程

本专题汇总PHP8.6升级迁移与弃用接口改造教程,涵盖反射调用、对象属性赋值、标识符更名、构造函数与__debugInfo调整,以及插件类名检查、常量导出、ArrayIterator排序、SPL和DTO查询参数转换,帮助梳理弃用提示并完成代码兼容改造。

2026.11.20

0

10

PHP8.6安装配置与FPM运维教程
PHP8.6安装配置与FPM运维教程

本专题汇总PHP8.6正式版安装部署与FPM运维教程,涵盖Linux并存安装、独立ini配置、扩展重新编译、Nginx切换与回滚、FPM状态监控和慢日志排查,以及环境变量、请求超时、OPcache刷新和预加载配置。

2026.11.20

0

10

Nginx CVE-2026-123007排查与防护指南
Nginx CVE-2026-123007排查与防护指南

Nginx HTTP/2漏洞该怎么修复?本专题围绕CVE-2026-123007,介绍安全版本升级、模块兼容检查和配置恢复方法,以及日志排查、权限设置等后续加固操作,方便你按实际部署情况查找对应教程。

2026.11.20

20

8

GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

2026.11.17

60

15

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.17

80

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
phpStudy极速入门视频教程
phpStudy极速入门视频教程

共6课时 | 54.7万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时 | 134.3万人学习