讲师中心 微信公众号
AI工具推荐 视频效率加速

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

星瑶吖_5979

星瑶吖_5979

发布时间:2016-05-25 17:00:18

|

2253人浏览过

|

来源于php中文网

原创

  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 controls="controls" autoplay="autoplay">
  <source src="<?php echo $t2s->speak('代码珠玑 , 提供编程中 需要的各种工具类 , 算法 , 函数 , 解决方案 , 技术文档 , 致力于做您最好的代码 , 分享平台',"zh-CN"); ?>" type="audio/mp3" />
</audio>

3.操作类

<?php
//http://www.codepearl.com
/******************************************************************
Example:
<?php 
$t2s = new PHP_Text2Speech;
?>
  
// Simple example
<audio controls="controls" autoplay="autoplay">
  <source src="<?php echo $t2s->speak('www.codepearl.com','en'); ?>" type="audio/mp3" />
</audio>
  
// Example use of other language
<audio controls="controls" autoplay="autoplay">
  <source src="<?php echo $t2s->speak('代码珠玑', 'zh-CN'); ?>" type="audio/mp3" />
</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) < $this->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 < strlen($contents); $i++){
            if(ord(substr($contents, $i, 1)) == 255){
                return $i;
            }
        }
    }
      
    /** Function to find the end of the mp3 file
     * @param   String  $contents       - File contents
     * @return  Integer
     */
    function getEnd($contents) {
        $c = substr($contents, (strlen($contents) - 128));
        if(strtoupper(substr($c, 0, 3)) == 'TAG'){
            return $c;
        }else{
            return FALSE;
        }
    }
  
    /** Function to remove the ID3 tags from mp3 files
     * @param   String  $contents       - File contents
     * @return  String
     */
    function stripTags($contents) {
        // Remove start
        $start = $this->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);
    }
}

热门AI工具

更多
UpDream
UpDream Hot

一款AI视频创作工具,主要用于哔哩哔哩推出的自研AI视频创作工具,适合需要提升相关任务效率的用户。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

SkildArt
SkildArt Hot

SkildArt是一款AI文本写作工具,一站式 AI 视觉创作平台。

蛙蛙写作

一款AI论文写作工具,主要用于超级AI智能写作助手,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

Seko
Seko Hot

一款AI视频创作工具,主要用于商汤科技推出的创编一体的AI短视频创作Agent,适合需要提升相关任务效率的用户。

讯飞智作

讯飞智作是一款AI视频创作工具,AI文本配音工具,数字人课程、营销视频制作。

音述AI
音述AI Hot

一款AI音频处理工具,主要用于音述AI是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区,适合需要提升相关任务效率的用户。

相关专题

更多
Buffalo框架数据库开发全教程
Buffalo框架数据库开发全教程

本专题围绕Buffalo框架数据库开发,讲解database.yml多环境配置、soda与fizz迁移生成回滚、模型结构体标签、增删改查与条件查询、一对多与多对多关联、数据校验、回调钩子、事务处理及原生SQL执行能力。

80

2026.09.23

Buffalo框架路由与请求处理实操指南
Buffalo框架路由与请求处理实操指南

本专题讲解Buffalo框架路由与请求处理机制,涵盖路由注册与分组、资源路由、Handler编写规范、Context上下文方法、参数绑定、中间件编写挂载、Session与Cookie读写、Flash消息及错误页面定制方法。

40

2026.09.23

Buffalo框架零基础入门教程
Buffalo框架零基础入门教程

本专题整理Buffalo框架入门内容,涵盖Go环境准备、buffalo CLI安装、新项目生成、目录结构说明、dev热加载启动、数据库连接配置与常见报错排查,帮助新手按约定优于配置的思路跑通第一个Buffalo框架应用。

20

2026.09.23

Conan创建软件包配方指南
Conan创建软件包配方指南

本专题介绍通过conanfile.py创建软件包的方法,讲解包名、版本、依赖和构建设置等基础信息,以及source、build、package、package_info等常用方法的作用及编写思路。

20

2026.09.22

Conan二进制包配置指南
Conan二进制包配置指南

本专题介绍Conan根据操作系统、编译器、架构和构建类型生成二进制包的方法,讲解Profile、Settings、Options及Package ID的作用,帮助管理不同平台和编译环境下的包版本。

40

2026.09.22

Conan私有仓库搭建教程
Conan私有仓库搭建教程

本专题系统的讲解Conan私有仓库的搭建流程,涵盖仓库服务部署、存储目录配置、用户认证、权限划分和远程地址添加,并介绍内部C++依赖包的上传、下载及版本维护方法。

40

2026.09.22

loomy官网入口地址合集
loomy官网入口地址合集

本专题汇总了 Loomy 桌面 AI 助理的官方入口地址合集及使用指南。提供 macOS 与 Windows 客户端下载 。Loomy 是讯飞推出的桌面级 AI 工作搭子,支持文件整理、数据分析、网页操作及通过飞书/钉钉远程操控电脑,助你高效完成本地办公任务 。

40

2026.09.22

NumPy常见函数使用方法
NumPy常见函数使用方法

本专题整理 NumPy 常见函数使用方法相关教程,覆盖函数大全、参数用法、数组运算、统计聚合、排序处理、where 条件筛选、linspace 创建数列等常用场景,帮助读者快速掌握 NumPy 函数调用思路和实际数据处理技巧。

60

2026.09.22

NumPy性能优化版本更新与常见报错排查
NumPy性能优化版本更新与常见报错排查

本专题整理 NumPy 性能优化、版本更新与常见报错排查相关教程,覆盖向量化计算、广播性能、内存布局、NumPy 2.0 升级、版本兼容冲突、安装导入报错、dtype 溢出、矩阵运算异常和 broadcasting 报错修复,帮助读者系统掌握 NumPy 性能调优与问题定位方法。

80

2026.09.22

热门下载

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

精品课程

更多
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn