腾讯云ASR产品-PHP实现录音文件识别极速版鉴权请求

一、准备工作

(1)开通腾讯云 https://cloud.tencent.com/

(2)腾讯云控制台开通实时语音权限 https://console.cloud.tencent.com/asr

(3)控制台设置秘钥 https://console.cloud.tencent.com/cam/capi

内容

说明

支持语言

中文普通话

音频格式

wav、pcm、ogg-opus、speex、silk、mp3、m4a、aac

使用限制

支持100MB以内音频文件的识别

请求协议

HTTPS

请求地址

https://asr.cloud.tencent.com/asr/flash/v1/<appid>?{请求参数}

二、代码

<?php

//极速版录音文件识别
class SpeedVoice
{
    //腾讯云密钥信息 需要配置
    const APPID = "您的APPID";
    const SECRET_ID = "您的SECRET_ID";
    const SECRET_KEY = "您的SECRET_KEY";

    const AGREEMENT = "https";
    const VOICE_URL = "asr.cloud.tencent.com/asr/flash/v1/";
    const HTTPRequestMethod = "POST";
    //引擎模型类型。8k_zh:8k 中文普通话通用;16k_zh:16k 中文普通话通用;16k_en:16k 英语;16k_zh_video:16k 音视频领域。
    static $ENGINE_MODEL_TYPE = '16k_zh';

    //结果返回方式 0:同步返回,拿到全部中间结果, or 1:尾包返回
    static $RES_TYPE = 1;

    // 支持 wav、pcm、ogg-opus、speex、silk、mp3、m4a、aac。
    static $VOICE_FORMAT = 'mp3';

    //是否开启说话人分离
    static $SPEAKER_DIARIZATION = 0;
    //后处理参数
    static $FILTER_DIRTY = 0;
    static $FILTER_MODAL = 0;
    static $FILTER_PUNC = 0;
    static $CONVERT_NUM_MODE = 1;
    static $WORD_INFO = 0;
    static $FIRST_CHANNEL_ONLY = 1;


    public static function voice($pathFile)
    {
        //get请求 设置url参数
        $timestamp = time();

        $httpUrlParams =
            [
                "appid" => self::APPID,
                "secretid" => self::SECRET_ID,
                "engine_type" => self::$ENGINE_MODEL_TYPE,
                "voice_format" => self::$VOICE_FORMAT,
                "timestamp" => $timestamp,
                "speaker_diarization"  => self::$SPEAKER_DIARIZATION,
                "filter_dirty"  => self::$FILTER_DIRTY,
                "filter_modal"  => self::$FILTER_MODAL,
                "filter_punc"   => self::$FILTER_PUNC,
                "convert_num_mode"  => self::$CONVERT_NUM_MODE,
                "word_info" => self::$WORD_INFO,
                "first_channel_only" => self::$FIRST_CHANNEL_ONLY
        ];
        //get请求url拼接
        $requestUrl = self::AGREEMENT . "://" . self::VOICE_URL . self::APPID . "?";
        //剔除appid
        unset($httpUrlParams["appid"]);
        //生成URL请求地址
        $requestUrl .= http_build_query($httpUrlParams);
        //鉴权
        $sign = self::getAuthorizationString($httpUrlParams);

        //分片数据包
        $sectionData = file_get_contents($pathFile);
        $headers = [
            'Host: asr.cloud.tencent.com',
            'Content-Type: application/octet-stream',
            'Authorization: ' . $sign,
            'Content-Length: ' . strlen($sectionData),
        ];
        $result = self::get_curl_request($requestUrl, $sectionData, 'POST', $headers);
        print_r($result);
    }


    /**
     * 发送请求
     * @param $url
     * @param array $param
     * @param string $mothod
     * @param array $headers
     * @param int $return_status
     * @param int $flag 关闭https证书
     * @return array|bool|string
     */
    static private function get_curl_request($url, $param, $mothod = 'POST', $headers = [], $return_status = 0, $flag = 0)
    {
        $ch = curl_init();
        if (!$flag) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }

        curl_setopt($ch, CURLOPT_TIMEOUT, 60);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (strtolower($mothod) == 'post') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        } else {
            $url = $url . "?" . http_build_query($param);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 2);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $ret = curl_exec($ch);
        $code = curl_getinfo($ch);
        curl_close($ch);
        if ($return_status == "1") {
            return array($ret, $code);
        }
        return $ret;
    }

    /**
     * 生成随机字符串
     * @param $len
     * @param bool $special 是否开启特殊字符
     * @return string
     */
    private static function getRandomString($len, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }

    /**
     * 创建签名
     * @param $params array 提交参数数组
     * @return string
     */
    private static function getAuthorizationString($params)
    {
        //加密字符串拼接
        $signString = self::HTTPRequestMethod . self::VOICE_URL . self::APPID . "?";
        //排序
        ksort($params, SORT_STRING);
        //去除appid
        unset($params["appid"]);
        //转url
        $signString .= http_build_query($params);
        $sign = base64_encode(hash_hmac('SHA1', $signString, self::SECRET_KEY, true));
        return $sign;
    }
}
//请求示例
SpeedVoice::$VOICE_FORMAT = "wav";
SpeedVoice::voice("./0914.wav");

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/212370.html

(0)
上一篇 2021年12月16日
下一篇 2021年12月16日

相关推荐

发表回复

登录后才能评论