让图片说出声音来(利用讯飞API实现图片转文字和文字转语音)

k思路:调用讯飞的图片识别和语音输出的API实现图片转文字和语音

**APPID,APIKey,APISecret自己在讯飞网站注册即可**,免费使用的,填在img_audio.php文件最后对应的位置就可以,链接是我自己制作的效果。

https://v.youku.com/v_show/id_XNTg2MjgxMjU3Mg==.html?spm=a2hcb.profile.app.5~5!2~5~5!3~5!2~5~5~A?%ra=link


代码如下

html里面使用到的是我的本地图片,自己根据需要修改就可以。

img_audio.html

<html>

<head>
<meta charset="utf-8">
<title>图片竟然会说话!!!</title>
<style>
.button 
{
    background-color: #B0C4DE;
    border: none;
    color: white;
    padding: 15px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    border-radius: 18px;
}

.button:hover {background-color: #5F9EA0}

.button:active {
  background-color:  #5F9EA0;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

</style>
</head>
<body background="timg.jpg">

<br>
<form action="img_audio.php" method="post" enctype="multipart/form-data" style="text-align: center">
    <label style="color:white" for="file" ></label>
<p style="text-align:center;color:white;font-family:STLiti;font-size:50px">你想听见哪张图片说话呢</p>

    <input type="file" class="button" name="file" id="file" style="text-align:center;font-family:STZhongsong;font-size:20px"><br>
<p style="text-align:center;color:white;font-family:STLiti;font-size:50px">你想听见哪个人的声音呢</p>

<select name="vcn" class="button" style="text-align:center;font-family:STZhongsong;font-size:20px">
  <option value="xiaoyan">小燕</option>
  <option value="aisjiuxu">许久</option>
  <option value="aisxping">小萍</option>
  <option value="aisjinger">小婧</option>
  <option value="aisbabyxu">许小宝</option>
</select>
<br><br><br>
    <input type="submit" class="button" name="submit" value="我选好了" style="text-align:center;font-family:STZhongsong;font-size:20px">
</form>



</body>
</html>

img_audio.php

<html>

<head>
<meta charset="utf-8">
<title>图片竟然会说话!!!</title>


<style>
.button {
    background-color: #B0C4DE;
    border: none;
    color: white;
    padding: 15px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    border-radius: 18px;
}

.button:hover {background-color: #5F9EA0}

.button:active {
  background-color:  #5F9EA0;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

</style>


</head>
<body background="timg.jpg" style="color:white">

<h1 style="text-align:center;color:white;font-family:STLiti;font-size:50px"><b>你听,图片也会说话</b></h1>

<p style="text-align:center;">
<img src="audio.jpg" width="310" height="200";><br>
<audio controls="controls"  class="button">
<source src="tts.mp3" type="audio/mp3" style="text-align:center;">
Your browser does not support the audio element.
</audio>

<h1 style="text-align:center;color:white;font-family:STLiti;font-size:50px"><b>它说的话在这里</b></h1>

</p>

<p style="text-align:center;color:white;font-family:STZhongsong;font-size:25px">

<?php
include "vendor/autoload.php";
include "vendor/textalk/websocket/lib/Base.php";
include "vendor/textalk/websocket/lib/Client.php";
include "vendor/textalk/websocket/lib/ConnectionException.php";


if(rename( $_FILES["file"]["tmp_name"],"./audio.jpg"));else echo "保存文件失败";

class img_text{
	function xfyun(){
		    $daytime=strtotime('1970-1-1T00:00:00 UTC');
			// 印刷文字识别 webapi 接口地址
		    $api = "http://webapi.xfyun.cn/v1/service/v1/ocr/general";
			// 应用ID (必须为webapi类型应用,并印刷文字识别服务,参考帖子如何创建一个webapi应用:http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481)
		    $XAppid = "5edf3ad1";
			// 接口密钥(webapi类型应用开通印刷文字识别服务后,控制台--我的应用---印刷文字识别---服务的apikey)
		    $Apikey = "9687c297598a2c247f332e50ee09ee1f";
		    $XCurTime =time();
		    $XParam ="";
		    $XCheckSum ="";
		    // 语言类型和文本位置信息(默认不返回)
		    $Param= array(
				"language"=>"cn|en",
				"location"=>"false",
		    );
			// 上传图片文件地址并base64位编码
		   $image=file_get_contents("audio.jpg");
		   $image=base64_encode($image);
		    
		    $Post = array(
			  'image' => $image,
			);

		    $XParam = base64_encode(json_encode($Param));
		    $XCheckSum = md5($Apikey.$XCurTime.$XParam);
			// 组装http请求头
		    $headers = array();
		    $headers[] = 'X-CurTime:'.$XCurTime;
		    $headers[] = 'X-Param:'.$XParam;
		    $headers[] = 'X-Appid:'.$XAppid;
		    $headers[] = 'X-CheckSum:'.$XCheckSum;
		    $headers[] = 'Content-Type:application/x-www-form-urlencoded; charset=utf-8';
		    return  $this->http_request($api, $Post, $headers);
		}

		/**
		 * 发送post请求
		 * @param string $url 请求地址
		 * @param array $post_data post键值对数据
		 * @return string
		 */
		function http_request($url, $post_data, $headers) {		 
		  $postdata = http_build_query($post_data);
		  $options = array(
		    'http' => array(
		      'method' => 'POST',
		      'header' => $headers,
		      'content' => $postdata,
		      'timeout' => 15 * 60 // 超时时间(单位:s)
		    )
		  );
		  $context = stream_context_create($options);
		  $result = file_get_contents($url, false, $context);

		  $result = explode('{"content":"',$result);
		  unset($result[0]);
		  //print_r($result);
		  $str = "";
		  foreach ($result as $word){
			$word = explode('"}',$word);
			$str = $str.$word[0];
			//print_r($word);
		  }
		  return $str;
		  //echo $str;

		 // 错误码链接:https://www.xfyun.cn/document/error-code (code返回错误码时必看)
		  return 'success';
		}
}

class text_audio{
    public $APPID;
    public $APIKey;
    public $APISecret;
    public $Text;
    public $vcn;
    # 初始化
    function __construct($APPID, $APIKey, $APISecret, $Text,$vcn){
        $this->APPID = $APPID;
        $this->APIKey = $APIKey;
        $this->APISecret = $APISecret;
        $this->Text = $Text;
        $this->vcn = $vcn;
    }
    # 生成url
    function create_url(){
        $url = 'wss://tts-api.xfyun.cn/v2/tts';
        # 生成RFC1123格式的时间戳
        $date = gmdate('D, d M Y H:i:s') . ' GMT';
        # 拼接字符串
        $signature_origin = "host: "."ws-api.xfyun.cn"."\n";
        $signature_origin."date: ".$date."\n";
        $signature_origin."GET "."/v2/tts "."HTTP/1.1";
        # 进行hmac-sha256进行加密 
        $signature_origin = "host: "."ws-api.xfyun.cn"."\n";
        $signature_origin = $signature_origin."date: ".$date."\n";
        $signature_origin = $signature_origin."GET "."/v2/tts "."HTTP/1.1";
        $signature_sha = base64_encode(hash_hmac('sha256', $signature_origin,$this->APISecret, true));

        $authorization_origin = "api_key=\"$this->APIKey\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"$signature_sha\"";
        $authorization = base64_encode($authorization_origin);
        # 将请求的鉴权参数组合为数组
        $v = [
            "authorization"=> $authorization,
            "date"=> $date,
            "host"=> "ws-api.xfyun.cn"];
        # 拼接鉴权参数,生成url
        $url = $url .'?'.http_build_query($v);

        return $url;
    }
    function get_message(){
        $url = $this->create_url();
        $client = new webSocket\Client($url);

        $data = [
            'common'=>[
                'app_id'=>$this->APPID
            ],
            'business'=>[
                'aue'=>"lame",  //mp3
                'sfl'=>1,
                'vcn'=>$this->vcn,
                'tte'=>"UTF8",
            ],
            'data'=>[
                'text'=>base64_encode($this->Text),
                'status'=>2
            ]
        ];
        $client = new WebSocket\Client($url);
        $client->send(json_encode($data));

        $result = "";
    while (true) {
        try {
            $message = json_decode($client->receive());
            //echo $message->data->audio;
            switch($message->data->status){
                case 0: break;
                case 1: $result.=base64_decode($message->data->audio);break;
                case 2: $result.=base64_decode($message->data->audio);break 2;
            }
            // Act on received message
            // Break while loop to stop listening
        } catch (\WebSocket\ConnectionException $e) {
        // Possibly log errors
        echo "错误<br>";
        sleep(3);
        break;
    }
}
        file_put_contents("tts.mp3",$result);
        $client->close();
    }
}

switch($_POST["vcn"]){
    case 'xiaoyan':
        $vcn='xiaoyan';break;
    case 'aisjiuxu':
        $vcn='aisjiuxu';break;
    case 'aisxping':
        $vcn='aisxping';break;
    case 'aisjinger':
        $vcn='aisjinger';break;
    case 'aisbabyxu':
        $vcn='aisbabyxu';break;
}


$test = new img_text();
$Text = $test->xfyun();
echo $Text;
$APPID="*********";
$APIKey="***********************************";
$APISecret="*************************************";
#上述三个均是在讯飞网站申请的,填入自己的即可
$b = new text_audio($APPID, $APIKey, $APISecret, $Text,$vcn);
$b->get_message();
?>

</p>



</body>
</html

JS语音文字是一种将语音换为文字的前端技术。JS(JavaScript)是一种常用的脚本语言,是一个著名的语音技术提供商。通过使用JS和提供的语音文字API,可以实现在网页或应用中通过语音输入来实现文字输入的功能。 使用JS语音文字的过程大致包括以下几个步骤: 1. 引入相关的JS脚本文件:将提供的语音文字的JS文件引入到网页中,以便使用相关的功能。 2. 初始化语音文字的配置:通过调用相应的JS函数,设置语音文字的初始化参数,例如语言、语音识别模型等。 3. 录音与语音识别:在网页中,添加录音按钮和语音识别按钮,用户可以点击录音按钮开始录音,然后将录音内容通过调用JS函数发送给的服务器进行语音识别。服务器会将语音换为文字,并返回识别结果。 4. 处理语音识别结果:通过JS函数获取语音识别的结果,并进行相应的处理,例如显示在网页上,或者发送给后台服务器进行进一步的处理。 5. 错误处理:在语音文字的过程中,可能会出现一些错误,例如网络错误或语音识别失败等。通过JS函数来捕获和处理这些错误,以提供更好的用户体验。 通过JS语音文字技术,可以实现语音文字的功能,方便用户进行语音输入。这在一些语音交互的应用场景中很常见,例如语音助手、语音搜索等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值