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

Expo环境下React Native调用GoogleCloudSpeechToText遇空对象错误求助

问题原因分析

你遇到的TypeError: null is not an object (evaluating 'GoogleCloudSpeechToText.setApiKey')错误,核心原因是react-native-google-cloud-speech-to-text是依赖原生代码实现的第三方库,而你当前使用的是Expo Managed Workflow——这种环境下无法直接使用需要原生链接(Linking)的模块,导致GoogleCloudSpeechToText对象未被正确初始化,调用其方法自然会报null错误。

解决方案

方案一:使用Expo官方支持的语音识别工具(推荐新手)

Expo提供了expo-speech-recognition,完全适配Managed Workflow,无需原生配置,直接就能用:

  1. 安装依赖
npx expo install expo-speech-recognition expo-permissions
  1. 修改代码替换原有逻辑
import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, Text, Button } from 'react-native';
import * as SpeechRecognition from 'expo-speech-recognition';
import * as Permissions from 'expo-permissions';

export default function Notes() {
  const [transcript, setResult] = useState("");

  useEffect(() => {
    async function requestPermissions() {
      const { status } = await Permissions.askAsync(Permissions.AUDIO_RECORDING);
      if (status !== 'granted') {
        alert('需要麦克风权限才能使用语音识别功能');
      }
    }
    requestPermissions();
  }, []);

  const startRecognizing = async () => {
    if (!(await SpeechRecognition.isAvailableAsync())) {
      alert('当前设备不支持语音识别');
      return;
    }
    await SpeechRecognition.startListeningAsync({
      language: 'zh-CN', // 根据需求设置语言,比如'en-US'
      onResult: (result) => {
        if (result.transcripts.length > 0) {
          setResult(result.transcripts[0]);
        }
      },
    });
  };

  const stopRecognizing = async () => {
    await SpeechRecognition.stopListeningAsync();
  };

  return (
    <SafeAreaView style={{ flex: 1, padding: 20 }}>
      <View style={{ marginBottom: 20 }}>
        <Text style={{ fontSize: 18, marginBottom: 10 }}>识别结果:{transcript}</Text>
        <Button title="开始识别" onPress={startRecognizing} />
      </View>
      <View>
        <Button title="停止识别" color="#f194ff" onPress={stopRecognizing} />
      </View>
    </SafeAreaView>
  );
}

方案二:切换到Bare Workflow(不推荐新手)

如果一定要坚持使用react-native-google-cloud-speech-to-text,需要将Expo项目转为原生项目:

  1. 执行 eject 命令
npx expo eject
  1. 按照该库的官方文档,手动配置Android和iOS的原生项目(包括添加麦克风权限、链接原生模块等)
  2. 重新运行原生项目

内容的提问来源于stack exchange,提问作者Cimo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:50:33