laravel接收录音文件并引用百度语音识别api

1.首先创建一个api  --routes\api.php

use \App\Http\Controllers\Wechat;
Route::any('/record',[wechat::class,'record']);

2.创建一个控制器  --App\Https\Controllers文件夹下创建Wechat

或者直接使用命令行

php artisan make:controller Wechat

3.Wechat.php中写入以下代码:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \GuzzleHttp\Client;
class Wechat extends Controller
{
    public function record(Request $request){
//接收文件
        $file=$request->file('file');
        if($file->isValid()){
            $clientName = $file -> getClientOriginalName();    //客户端文件名称..
            $entension = $file -> getClientOriginalExtension();   //上传文件的后缀.
            $newName = $newName = md5(date('ymdhis').$clientName).".".$entension;    //定义上传文件的新名称
            $path = $file -> move('storage/uploads',$newName);
            $path=str_replace('\\', '/', $path);
        }else{
            return ['上传失败'];
        }
        # 需要识别的文件897687576c6e80686b64ad0a0d00d813.mp3
        $AUDIO_FILE = asset('/'.$path);
//        $AUDIO_FILE=$request->file('file')-> getRealPath();
# 文件格式

        $FORMAT = substr($AUDIO_FILE, -3); // 文件后缀 pcm/wav/amr 格式 极速版额外支持m4a 格式

        $CUID = "123456PHP";
# 采样率
        $RATE = 16000;  // 固定值

# 普通版
        $ASR_URL = "http://vop.baidu.com/server_api";
# 根据文档填写PID,选择语言及识别模型
        $DEV_PID = 1537; //  1537 表示识别普通话,使用输入法模型。
        $SCOPE = 'audio_voice_assistant_get'; // 有此scope表示有语音识别普通版能力,没有请在网页里开通语音识别能力


        $SCOPE = false; // 部分历史应用没有加入scope,设为false忽略检查
        /** 公共模块获取token开始 */

# 填写网页上申请的appkey 如 $apiKey="g8eBUMSokVB1BHGmgxxxxxx"
        $API_KEY =  "VXBpoojxLSpn1fbxz2inU0GV";

# 填写网页上申请的APP SECRET 如 $secretKey="94dc99566550d87f8fa8ece112xxxxx"
        $SECRET_KEY = "eTI5pissHaeDkN2hwaiBb34XeIUWgP8G";
        $auth_url = "http://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=".$API_KEY."&client_secret=".$SECRET_KEY;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $auth_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 检查证书中是否设置域名,0不验证
        $res = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);

//        echo "Token URL response is " . $res . "\n";
        $response = json_decode($res, true);

        if (!isset($response['access_token'])){
            echo "ERROR TO OBTAIN TOKEN\n";
            exit(1);
        }
        if (!isset($response['scope'])){
            echo "ERROR TO OBTAIN scopes\n";
            exit(2);
        }

        if ($SCOPE && !in_array($SCOPE, explode(" ", $response['scope']))){
            echo "CHECK SCOPE ERROR\n";
            // 请至网页上应用内开通语音识别权限
            exit(3);
        }

        $token = $response['access_token'];
//        echo "token = $token ; expireInSeconds: ${response['expires_in']}\n\n";
        /** 公共模块获取token结束 */
        /** 拼接参数开始 **/
        $audio = file_get_contents($AUDIO_FILE);
        $base_data = base64_encode($audio);
        $params = array(
            "dev_pid" => $DEV_PID,
            //"lm_id" => $LM_ID,    //测试自训练平台开启此项
            "format" => $FORMAT,
            "rate" => $RATE,
            "token" => $token,
            "cuid"=> $CUID,
            "speech" => $base_data,
            "len" => strlen($audio),
            "channel" => 1,
        );

        $json_array = json_encode($params);
        $headers[] = "Content-Length: ".strlen($json_array);
        $headers[] = 'Content-Type: application/json; charset=utf-8';

        /** 拼接参数结束 **/

        /** asr 请求开始 **/

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $ASR_URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 识别时长不超过原始音频
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_array);
//        curl_setopt($ch, CURLOPT_VERBOSE, DEMO_CURL_VERBOSE);
        $res = curl_exec($ch);
        if(curl_errno($ch))
        {
            echo curl_error($ch);
            exit (2);
        }
        curl_close($ch);
        /** asr 请求结束 **/

// 解析结果
        $response = json_decode($res, true);

        if (isset($response['err_no']) && $response['err_no'] == 0){
            return $response['result'][0];
        }else{
            echo "asr has error\n";
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值