You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Speech-to-Text中使用Yii2缓存的音频数据?

从Yii2缓存获取音频数据实现Google语音转文本

需求背景

现有Google官方的异步语音转文本PHP代码,需要修改为直接从Yii2缓存中读取音频数据,无需通过临时文件中转(此前临时文件方案未成功)。

修改后的完整代码

use Google\Cloud\Speech\V1\SpeechClient;
use Google\Cloud\Speech\V1\RecognitionAudio;
use Google\Cloud\Speech\V1\RecognitionConfig;
use Google\Cloud\Speech\V1\RecognitionConfig\AudioEncoding;
use Yii;

/**
 * @param string $cacheKey Yii2缓存中存储音频数据的键名
 */
function transcribe_async_from_cache(string $cacheKey)
{
    // 配置参数可根据实际音频调整
    $encoding = AudioEncoding::LINEAR16;
    $sampleRateHertz = 32000;
    $languageCode = 'en-US';

    // 从Yii2缓存获取音频内容
    $content = Yii::$app->cache->get($cacheKey);
    
    // 校验缓存数据是否存在
    if ($content === false) {
        printf('缓存中未找到指定键的音频数据' . PHP_EOL);
        return;
    }

    // 直接将缓存中的音频内容传入RecognitionAudio
    $audio = (new RecognitionAudio())
        ->setContent($content);

    // 配置语音识别参数
    $config = (new RecognitionConfig())
        ->setEncoding($encoding)
        ->setSampleRateHertz($sampleRateHertz)
        ->setLanguageCode($languageCode);

    // 初始化Speech客户端
    $client = new SpeechClient();

    try {
        // 发起异步识别请求并等待完成
        $operation = $client->longRunningRecognize($config, $audio);
        $operation->pollUntilComplete();

        if ($operation->operationSucceeded()) {
            $response = $operation->getResult();

            // 遍历识别结果输出
            foreach ($response->getResults() as $result) {
                $alternatives = $result->getAlternatives();
                $mostLikely = $alternatives[0];
                $transcript = $mostLikely->getTranscript();
                $confidence = $mostLikely->getConfidence();
                printf('转录文本: %s' . PHP_EOL, $transcript);
                printf('置信度: %s' . PHP_EOL, $confidence);
            }
        } else {
            print_r($operation->getError());
        }
    } finally {
        // 确保客户端连接关闭
        $client->close();
    }
}

关键修改点说明

  • 直接读取缓存内容:用Yii::$app->cache->get($cacheKey)替代原代码的file_get_contents($audioFile),直接获取缓存中的音频二进制字符串,绕开临时文件操作。
  • 增加缓存校验:判断缓存返回值是否为false(Yii2缓存未命中时的标准返回值),提前处理数据缺失的情况,避免后续流程报错。
  • 优化资源释放:将客户端关闭逻辑放入finally块,确保无论请求成功或失败,都能正确释放客户端连接资源。

使用示例

调用时只需传入缓存中存储音频数据的键名即可:

transcribe_async_from_cache('user_audio_123');

内容的提问来源于stack exchange,提问作者Павел Осипов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:53:08