logo

uniapp集成百度语音识别:Vue2跨平台开发实战指南

作者:有好多问题2025.09.23 13:14浏览量:0

简介:本文详细介绍如何在uniapp(Vue2)项目中集成百度语音识别API,实现Android/iOS双端语音转文字功能。包含环境配置、权限申请、API调用及错误处理全流程,提供可复用的代码示例和优化建议。

一、技术选型与前期准备

1.1 百度语音识别API选择

百度AI开放平台提供两种语音识别方案:

对于移动端应用,短语音识别(speech_recognizer_short)是更优选择,其优势在于:

  • 响应速度快(<1秒)
  • 流量消耗低(约1KB/秒)
  • 集成复杂度低

1.2 uniapp环境要求

需确保项目满足:

  • HBuilderX 3.2.0+版本
  • Vue2语法规范
  • 目标平台配置(Android/iOS)

1.3 百度账号注册

  1. 访问百度AI开放平台
  2. 创建应用并获取:
    • APP_ID:应用唯一标识
    • API_KEY:接口调用凭证
    • SECRET_KEY:密钥(需保密)

二、核心实现步骤

2.1 权限配置

Android配置

manifest.json中添加:

  1. "app-plus": {
  2. "permissions": [
  3. "<uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>",
  4. "<uses-permission android:name=\"android.permission.INTERNET\"/>"
  5. ]
  6. }

iOS配置

manifest.json中添加:

  1. "ios": {
  2. "NSMicrophoneUsageDescription": "需要麦克风权限进行语音识别"
  3. }

2.2 核心代码实现

2.2.1 工具类封装

创建baiduVoice.js

  1. import { getAccessToken } from '@/api/baiduAuth'
  2. export default {
  3. async recognize(audioData) {
  4. try {
  5. const token = await getAccessToken()
  6. const url = `https://vop.baidu.com/server_api?cuid=${deviceId}&token=${token}`
  7. const formData = new FormData()
  8. formData.append('audio', audioData, 'record.wav')
  9. formData.append('format', 'wav')
  10. formData.append('rate', 16000)
  11. formData.append('channel', 1)
  12. formData.append('token', token)
  13. formData.append('cuid', deviceId)
  14. formData.append('len', audioData.length)
  15. const res = await uni.request({
  16. url,
  17. method: 'POST',
  18. data: formData,
  19. header: {
  20. 'Content-Type': 'multipart/form-data'
  21. }
  22. })
  23. return res[1].data
  24. } catch (e) {
  25. console.error('语音识别失败:', e)
  26. throw e
  27. }
  28. }
  29. }

2.2.2 录音组件实现

  1. <template>
  2. <view>
  3. <button @click="startRecord">开始录音</button>
  4. <button @click="stopRecord" :disabled="!isRecording">停止录音</button>
  5. <text v-if="result">识别结果:{{result}}</text>
  6. </view>
  7. </template>
  8. <script>
  9. import recorder from '@/utils/recorder'
  10. import voiceApi from '@/utils/baiduVoice'
  11. export default {
  12. data() {
  13. return {
  14. isRecording: false,
  15. audioPath: '',
  16. result: ''
  17. }
  18. },
  19. methods: {
  20. async startRecord() {
  21. try {
  22. this.audioPath = await recorder.start({
  23. format: 'wav',
  24. sampleRate: 16000
  25. })
  26. this.isRecording = true
  27. } catch (e) {
  28. uni.showToast({ title: '录音失败', icon: 'none' })
  29. }
  30. },
  31. async stopRecord() {
  32. const filePath = await recorder.stop()
  33. const audioData = await this.readFile(filePath)
  34. try {
  35. const res = await voiceApi.recognize(audioData)
  36. this.result = res.result[0]
  37. } catch (e) {
  38. uni.showToast({ title: '识别失败', icon: 'none' })
  39. } finally {
  40. this.isRecording = false
  41. }
  42. },
  43. readFile(path) {
  44. return new Promise((resolve, reject) => {
  45. plus.io.resolveLocalFileSystemURL(path, entry => {
  46. entry.file(file => {
  47. const reader = new plus.io.FileReader()
  48. reader.onloadend = e => resolve(new Uint8Array(e.target.result))
  49. reader.onerror = reject
  50. reader.readAsArrayBuffer(file)
  51. })
  52. }, reject)
  53. })
  54. }
  55. }
  56. }
  57. </script>

2.3 百度认证服务

创建baiduAuth.js

  1. let token = ''
  2. let expireTime = 0
  3. export async function getAccessToken() {
  4. if (Date.now() < expireTime && token) {
  5. return token
  6. }
  7. const res = await uni.request({
  8. url: 'https://aip.baidubce.com/oauth/2.0/token',
  9. method: 'POST',
  10. data: {
  11. grant_type: 'client_credentials',
  12. client_id: 'YOUR_API_KEY',
  13. client_secret: 'YOUR_SECRET_KEY'
  14. }
  15. })
  16. token = res[1].data.access_token
  17. expireTime = Date.now() + res[1].data.expires_in * 1000 - 60000 // 提前1分钟刷新
  18. return token
  19. }

三、常见问题解决方案

3.1 录音权限被拒处理

  1. // 在录音前检查权限
  2. async checkPermission() {
  3. const status = await uni.authorize({
  4. scope: 'scope.record'
  5. })
  6. if (status !== 'authorized') {
  7. uni.showModal({
  8. title: '权限请求',
  9. content: '需要麦克风权限进行语音识别',
  10. success: async ({ confirm }) => {
  11. if (confirm) {
  12. await uni.openSetting()
  13. }
  14. }
  15. })
  16. }
  17. }

3.2 音频格式要求

百度语音识别要求:

  • 采样率:16000Hz(必须)
  • 格式:wav/pcm/amr/speex
  • 位深:16bit
  • 声道:单声道

转换工具推荐:

  1. // 使用ffmpeg.js进行格式转换(需引入webassembly版本)
  2. async function convertAudio(inputPath) {
  3. const { data } = await uni.getFileSystemManager().readFile({
  4. filePath: inputPath
  5. })
  6. // 这里添加ffmpeg转换逻辑
  7. return convertedData
  8. }

3.3 错误码处理

错误码 含义 解决方案
100 参数错误 检查format/rate参数
110 认证失败 检查token有效性
111 配额超限 升级服务等级
120 音频过长 控制录音时长<60秒

四、性能优化建议

  1. 预加载token:在App启动时获取token
  2. 本地缓存:对频繁识别的内容做本地缓存
  3. 分片上传:对于长音频采用分片上传策略
  4. 降噪处理:使用WebAudio API进行前端降噪
    1. // 简单降噪示例
    2. function applyNoiseSuppression(audioBuffer) {
    3. const channelData = audioBuffer.getChannelData(0)
    4. const threshold = 0.02
    5. for (let i = 0; i < channelData.length; i++) {
    6. if (Math.abs(channelData[i]) < threshold) {
    7. channelData[i] = 0
    8. }
    9. }
    10. return audioBuffer
    11. }

五、部署注意事项

  1. iOS配置

    • Info.plist中添加:
      1. <key>NSMicrophoneUsageDescription</key>
      2. <string>需要麦克风权限进行语音输入</string>
    • 确保Build Settings中ENABLE_BITCODE设为NO
  2. Android配置

    • AndroidManifest.xml中添加:
      1. <uses-permission android:name="android.permission.INTERNET" />
      2. <uses-permission android:name="android.permission.RECORD_AUDIO" />
      3. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  3. 真机调试

    • 必须使用真机测试,模拟器可能无法获取麦克风权限
    • 首次使用需手动授权麦克风权限

六、扩展功能建议

  1. 多语言支持

    1. // 在请求中添加lang参数
    2. formData.append('lan', 'zh') // 中文
    3. // 可选值:zh, en, canto, etc.
  2. 实时显示识别结果

    1. // 使用WebSocket实现流式识别
    2. async function startStreamRecognize() {
    3. const ws = new WebSocket('wss://vop.baidu.com/stream_api_v1')
    4. ws.onmessage = (e) => {
    5. const data = JSON.parse(e.data)
    6. if (data.result) {
    7. this.partialResult = data.result[0]
    8. }
    9. }
    10. // 发送音频分片...
    11. }
  3. 语音指令控制

    1. // 结合NLP实现指令识别
    2. async function recognizeCommand() {
    3. const text = await this.recognize()
    4. const commands = {
    5. '打开设置': () => uni.switchTab({ url: '/pages/settings' }),
    6. '返回主页': () => uni.switchTab({ url: '/pages/home' })
    7. }
    8. for (const [cmd, action] of Object.entries(commands)) {
    9. if (text.includes(cmd)) {
    10. action()
    11. break
    12. }
    13. }
    14. }

通过以上实现方案,开发者可以在uniapp(Vue2)项目中快速集成百度语音识别功能,实现高质量的语音转文字服务。实际开发中需注意权限管理、错误处理和性能优化等关键点,以确保应用的稳定性和用户体验。

相关文章推荐

发表评论