Laravel语音识别用API吗

wen PHP项目 8

本文目录导读:

Laravel语音识别用API吗

  1. 主流语音识别 API 选择
  2. 封装成 Laravel Service
  3. 使用 WebSocket 实时语音识别
  4. 配置文件 config/services.php
  5. Controller 调用示例
  6. 推荐方案

在 Laravel 中集成语音识别功能,通常需要使用第三方 API,因为 Laravel 本身不内置语音识别能力,以下是几种常见的实现方式:

主流语音识别 API 选择

阿里云语音识别(推荐国内用户)

use AlibabaCloud\Client\AlibabaCloud;
// 安装: composer require alibabacloud/sdk
AlibabaCloud::accessKeyClient('your-key', 'your-secret')
    ->regionId('cn-shanghai')
    ->asGlobalClient();
$result = AlibabaCloud::rpc()
    ->product('nls-filetrans')
    ->version('2018-08-17')
    ->action('createTask')
    ->method('POST')
    ->options([
        'query' => [
            'Task' => json_encode([
                'appkey' => 'your-appkey',
                'file_link' => 'https://your-bucket.oss-cn-shanghai.aliyuncs.com/audio.mp3'
            ])
        ]
    ])
    ->request();

腾讯云语音识别

use TencentCloud\Common\Credential;
use TencentCloud\Asr\V20190614\AsrClient;
// 安装: composer require tencentcloud/tencentcloud-sdk-php
$cred = new Credential("your-secret-id", "your-secret-key");
$client = new AsrClient($cred, "ap-guangzhou");
$req = new CreateRecTaskRequest();
$params = json_encode([
    "EngineModelType" => "16k_0",
    "ChannelNum" => 1,
    "ResTextFormat" => 0,
    "SourceType" => 0,
    "Url" => "https://your-file-url.mp3"
]);
$req->fromJsonString($params);
$resp = $client->CreateRecTask($req);

封装成 Laravel Service

创建服务类 app/Services/SpeechRecognitionService.php:

namespace App\Services;
use Illuminate\Support\Facades\Http;
class SpeechRecognitionService
{
    protected $apiKey;
    protected $apiUrl;
    public function __construct()
    {
        $this->apiKey = config('services.speech.api_key');
        $this->apiUrl = config('services.speech.api_url');
    }
    public function recognize($audioFile)
    {
        // 上传文件到云存储(OSS/S3)
        $audioUrl = $this->uploadToCloud($audioFile);
        // 调用语音识别 API
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->apiKey
        ])->post($this->apiUrl . '/recognize', [
            'audio_url' => $audioUrl,
            'language' => 'zh-CN'
        ]);
        return $response->json();
    }
    private function uploadToCloud($file)
    {
        // 实现文件上传逻辑
    }
}

使用 WebSocket 实时语音识别

use Ratchet\Client\WebSocket;
use React\EventLoop\Loop;
$loop = Loop::get();
$connector = new WebSocket\Connector($loop);
$connector('wss://speech-api.example.com/ws?key=your-key')
    ->then(function(WebSocket $conn) use ($audioStream) {
        $conn->on('message', function($msg) {
            Log::info('识别结果: ' . $msg);
        });
        // 发送音频流
        foreach ($audioStream as $chunk) {
            $conn->send($chunk);
        }
    }, function($e) {
        echo "连接失败: {$e->getMessage()}\n";
    });
$loop->run();

配置文件 config/services.php

'speech' => [
    'driver' => env('SPEECH_DRIVER', 'aliyun'), // aliyun, tencent, google
    'aliyun' => [
        'access_key' => env('ALIYUN_ACCESS_KEY'),
        'access_secret' => env('ALIYUN_ACCESS_SECRET'),
        'app_key' => env('ALIYUN_APP_KEY'),
    ],
    'tencent' => [
        'secret_id' => env('TENCENT_SECRET_ID'),
        'secret_key' => env('TENCENT_SECRET_KEY'),
    ],
    'api_url' => env('SPEECH_API_URL'),
    'api_key' => env('SPEECH_API_KEY'),
],

Controller 调用示例

use App\Services\SpeechRecognitionService;
use Illuminate\Http\Request;
class SpeechController extends Controller
{
    public function recognize(Request $request, SpeechRecognitionService $service)
    {
        $request->validate([
            'audio' => 'required|file|mimes:wav,mp3,ogg|max:10240'
        ]);
        $result = $service->recognize($request->file('audio'));
        return response()->json([
            'success' => true,
            'text' => $result['text'] ?? '',
            'confidence' => $result['confidence'] ?? 0
        ]);
    }
}

推荐方案

场景 推荐 API
国内生产环境 阿里云、腾讯云、百度云
国际项目 Google Cloud Speech-to-Text、Azure Speech
预算有限 讯飞开放平台(有免费额度)
实时性要求高 使用 WebSocket 方案

注意事项:

  • 语音文件通常较大,建议先上传到对象存储再识别
  • 考虑语音识别结果的异步回调处理
  • 注意各 API 的并发限制和计费方式

如果你需要针对特定场景(如实时语音识别、电话录音转写等)的实现细节,可以进一步说明你的需求。

抱歉,评论功能暂时关闭!