uniapp 如何实现百度语音识别功能

请问在uniapp中如何集成百度语音识别功能?目前项目需要实现语音输入转文字的功能,看了百度AI开放平台的文档,但不太清楚具体在uniapp中该如何调用。是否需要通过原生插件实现?有没有完整的接入示例或步骤可以参考?求大神指点具体实现方案。

2 回复

在uniapp中,可以通过插件市场搜索“百度语音识别”插件,或使用uni.request调用百度语音识别API。需要先在百度云申请API Key和Secret Key,然后通过接口发送音频数据获取识别结果。注意处理跨域和音频格式兼容问题。


在 UniApp 中实现百度语音识别功能,可以通过调用百度语音识别 API 实现。以下是具体步骤和示例代码:

实现步骤

  1. 注册百度云账号并创建应用
    访问百度AI开放平台(ai.baidu.com),注册账号,创建语音识别应用,获取 API Key 和 Secret Key。

  2. 获取 Access Token
    使用 API Key 和 Secret Key 调用百度认证接口获取 access_token(有效期为30天)。

  3. 录制音频并转码
    使用 UniApp 的 uni.record API 录制音频,将录制的音频转换为百度支持的格式(如 PCM/WAV)。

  4. 调用语音识别 API
    将音频数据通过 Base64 编码,调用百度语音识别接口进行识别。

示例代码

1. 获取 Access Token

async function getAccessToken(apiKey, secretKey) {
  const url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apiKey}&client_secret=${secretKey}`;
  try {
    const res = await uni.request({ url, method: 'GET' });
    return res.data.access_token;
  } catch (err) {
    console.error('获取Token失败:', err);
    return null;
  }
}

2. 录制音频并识别

export default {
  data() {
    return {
      recorderManager: null,
      tempFilePath: ''
    };
  },
  methods: {
    // 开始录音
    startRecord() {
      this.recorderManager = uni.getRecorderManager();
      this.recorderManager.start({
        format: 'wav', // 百度支持WAV/PCM格式
        sampleRate: 16000, // 采样率
        numberOfChannels: 1 // 单声道
      });
      this.recorderManager.onStop((res) => {
        this.tempFilePath = res.tempFilePath;
        this.recognizeAudio();
      });
    },

    // 停止录音并识别
    stopRecord() {
      this.recorderManager.stop();
    },

    // 调用百度语音识别
    async recognizeAudio() {
      const accessToken = await getAccessToken('你的API_KEY', '你的SECRET_KEY');
      if (!accessToken) return;

      // 将音频文件转为Base64
      const base64 = await this.fileToBase64(this.tempFilePath);
      
      const url = `https://vop.baidu.com/server_api?dev_pid=1537&cuid=UNIAPP_DEMO&token=${accessToken}`;
      const data = {
        format: 'wav',
        rate: 16000,
        channel: 1,
        speech: base64.replace('data:audio/wav;base64,', ''),
        len: Math.floor(base64.length * 0.75) // Base64解码后长度估算
      };

      uni.request({
        url,
        method: 'POST',
        header: { 'Content-Type': 'application/json' },
        data: JSON.stringify(data),
        success: (res) => {
          if (res.data.err_no === 0) {
            console.log('识别结果:', res.data.result);
            uni.showToast({ title: '识别成功: ' + res.data.result[0], icon: 'none' });
          } else {
            console.error('识别失败:', res.data);
          }
        }
      });
    },

    // 文件转Base64
    fileToBase64(tempFilePath) {
      return new Promise((resolve) => {
        uni.getFileSystemManager().readFile({
          filePath: tempFilePath,
          encoding: 'base64',
          success: (res) => resolve(`data:audio/wav;base64,${res.data}`)
        });
      });
    }
  }
};

注意事项

  • 格式要求:百度语音识别支持 PCM/WAV/AMR 等格式,需确保录音参数匹配。
  • 采样率:推荐使用 16000Hz 或 8000Hz。
  • 网络请求:需在 manifest.json 中配置网络请求权限。
  • 安全提醒:将 API Key 和 Secret Key 存储在服务端,通过自有服务器转发请求更安全。

通过以上步骤,即可在 UniApp 中集成百度语音识别功能。

回到顶部