Laravel 8集成Google Cloud Speech API报REST不支持流调用错误如何解决?
问题解决方案
根因
你遇到的"Streaming calls are not supported while using the REST transport."报错,是因为Google Cloud Speech API的流式识别能力仅支持gRPC传输协议,PHP版SDK默认在未检测到gRPC扩展时会自动降级到REST协议,因此触发该报错。
修复步骤
- 第一步:安装gRPC和protobuf扩展
执行以下命令安装扩展:
pecl install grpc protobuf
安装完成后在你的php.ini配置文件中添加两行扩展加载配置:
extension=grpc.so extension=protobuf.so # Windows系统对应改为 extension=grpc.dll、extension=protobuf.dll
安装完成后执行php -m命令,确认grpc、protobuf出现在扩展列表中。
- 第二步:修改SpeechClient初始化配置,强制指定传输协议为gRPC
修改你初始化SpeechClient的代码,新增transport参数:
$speechClient = new SpeechClient([ 'credentials' => Storage::path('public/auth.json'), 'transport' => 'grpc' // 强制使用gRPC协议 ]);
- 第三步:修改音频读取方式为资源流
你当前使用Storage::get()拿到的是音频文件的字符串内容,流式识别接口需要传入可读资源类型,修改对应代码:
// 替换原来的$file = Storage::disk('public')->get('test.flac'); $file = fopen(Storage::path('public/test.flac'), 'r');
修复后完整transcribedText方法参考
public function transcribedText(Request $request) { $recognitionConfig = new RecognitionConfig(); $recognitionConfig->setEncoding(AudioEncoding::FLAC); $recognitionConfig->setSampleRateHertz(44100); $recognitionConfig->setLanguageCode('en-US'); $config = new StreamingRecognitionConfig(); $config->setConfig($recognitionConfig); $speechClient = new SpeechClient([ 'credentials' => Storage::path('public/auth.json'), 'transport' => 'grpc' ]); $file = fopen(Storage::path('public/test.flac'), 'r'); $responses = $speechClient->recognizeAudioStream($config, $file); foreach ($responses as $element) { dd($element); } }
内容的提问来源于stack exchange,提问作者LaFllamme
相关产品推荐
相关产品推荐

