阿里云tts 将文字转换成语音

php

浏览数:3,314

2019-1-13


要先注册阿里云帐号,开通智能语音服务

<?php
class tts{

    private $access_id = '';

    private $ak_secret = '';

    private $audioType = '';

    public function __construct($access_id,$ak_secret,$audioType)
    {
        $this->access_id = $access_id;
        $this->ak_secret = $ak_secret;
        $this->audioType = $audioType;
    }

    public function curlRequest($url, $params , $is_post = false, $time_out = 10, $header=array())
    {
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';

        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置是否返回response header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上

        //当需要通过curl_getinfo来获取发出请求的header信息时,该选项需要设置为true
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);

        curl_setopt($ch, CURLOPT_TIMEOUT, $time_out);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $time_out);
        curl_setopt($ch, CURLOPT_POST, $is_post);

        if ($is_post) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }

        if ($str_cookie) {
            curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        }

        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        $response = curl_exec($ch);

        curl_close($ch);

        return $response;
    }

    public function tts_voice($body,$file){

        $bodyMd5 = base64_encode(md5($body,true));

        $method = "POST";

        $audioType = $this->audioType;

        $content_type = "text/plain";

        $date = gmdate("D, d M Y H:i:s \G\M\T");

        $accept = "audio/" . $audioType.';samplerate=16000' . ", application/json";

        $stringToSign = $method."\n".$accept."\n".$bodyMd5."\n".$content_type."\n".$date;

        $access_id = $this->access_id;

        $ak_secret = $this->ak_secret;

        $signature = base64_encode(hash_hmac('sha1',$stringToSign,$ak_secret,true));        $header = [
            'Date: '.$date,
            'Content-type: '.$content_type,
            'Authorization: Dataplus '.$access_id.':'.$signature,
            'Accept: '.$accept,
            'Content-Length: '.strlen($body)
        ];

        $url = 'http://nlsapi.aliyun.com/speak?encode_type='.$this->audioType.'&voice_name=xiaoyun&volume=50';

        $re = $this->curlRequest($url, $body, true, 60, $header);

        $file = $file.'.'.$this->audioType;

        $f = fopen($file, 'w');

        fwrite($f, $re);

        fclose($f);

    }
}

$access_id = 'xxxxxxxxxxxxxx';//阿里云的access_id

$ak_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';//阿里云的access_key

$audioType = 'mp3';

$text = '床前明月光,疑是地上霜。举头望明月,低头思故乡。';

$obj = new \tts($access_id,$ak_secret,$audioType);

$obj->tts_voice($text,'12');//要转换的文本,生成的文件名