当前位置:网站首页>Tencent cloud ASR product -php realizes the authentication request of the extremely fast version of recording file identification

Tencent cloud ASR product -php realizes the authentication request of the extremely fast version of recording file identification

2022-06-24 03:19:00 Yuanlunqiao

One 、 preparation

(1) Open Tencent cloud https://cloud.tencent.com/

(2) Tencent cloud console opens real-time voice permission https://console.cloud.tencent.com/asr

(3) The console sets the secret key https://console.cloud.tencent.com/cam/capi

Content

explain

Support language

Mandarin Chinese

Audio format

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

Usage restriction

Support 100MB Identification of internal audio files

Request protocol

HTTPS

Request address

https://asr.cloud.tencent.com/asr/flash/v1/<appid>?{ Request parameters }

Two 、 Code

<?php

// Speed recording file recognition 
class SpeedVoice
{
    // Tencent cloud key information   Need configuration 
    const APPID = " Your APPID";
    const SECRET_ID = " Your SECRET_ID";
    const SECRET_KEY = " Your SECRET_KEY";

    const AGREEMENT = "https";
    const VOICE_URL = "asr.cloud.tencent.com/asr/flash/v1/";
    const HTTPRequestMethod = "POST";
    // Engine model type .8k_zh:8k  Mandarin Chinese is common ;16k_zh:16k  Mandarin Chinese is common ;16k_en:16k  English ;16k_zh_video:16k  Audio and video .
    static $ENGINE_MODEL_TYPE = '16k_zh';

    // Result return method  0: Sync back , Get all the intermediate results , or 1: Tail package return 
    static $RES_TYPE = 1;

    //  Support  wav、pcm、ogg-opus、speex、silk、mp3、m4a、aac.
    static $VOICE_FORMAT = 'mp3';

    // Whether to enable speaker separation 
    static $SPEAKER_DIARIZATION = 0;
    // Post processing parameters 
    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 request   Set up url Parameters 
        $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 request url Splicing 
        $requestUrl = self::AGREEMENT . "://" . self::VOICE_URL . self::APPID . "?";
        // To eliminate appid
        unset($httpUrlParams["appid"]);
        // Generate URL Request address 
        $requestUrl .= http_build_query($httpUrlParams);
        // authentication 
        $sign = self::getAuthorizationString($httpUrlParams);

        // Fragmented packet 
        $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);
    }


    /**
     *  Send a request 
     * @param $url
     * @param array $param
     * @param string $mothod
     * @param array $headers
     * @param int $return_status
     * @param int $flag  close https certificate 
     * @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;
    }

    /**
     *  Generate random string 
     * @param $len
     * @param bool $special  Whether to open special characters 
     * @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);                            // Disorder array order 
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    // Take out one at random 
        }
        return $str;
    }

    /**
     *  Create signature 
     * @param $params array  Commit parameter array 
     * @return string
     */
    private static function getAuthorizationString($params)
    {
        // Encrypted string concatenation 
        $signString = self::HTTPRequestMethod . self::VOICE_URL . self::APPID . "?";
        // Sort 
        ksort($params, SORT_STRING);
        // Remove appid
        unset($params["appid"]);
        // turn url
        $signString .= http_build_query($params);
        $sign = base64_encode(hash_hmac('SHA1', $signString, self::SECRET_KEY, true));
        return $sign;
    }
}
// Request example 
SpeedVoice::$VOICE_FORMAT = "wav";
SpeedVoice::voice("./0914.wav");
原网站

版权声明
本文为[Yuanlunqiao]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/10/20211011181654688S.html