微信小程序语音交互全攻略:从转文字到语音播报的实现

一、语音转文字功能实现

1.1 核心API与权限配置

微信小程序提供wx.getRecorderManager()wx.onVoiceRecordEnd实现录音,结合后端ASR(自动语音识别)服务完成转写。需在app.json中声明录音权限:

  1. {
  2. "permission": {
  3. "scope.record": {
  4. "desc": "需要录音权限以实现语音转文字"
  5. }
  6. }
  7. }

1.2 录音管理流程

通过RecorderManager控制录音生命周期:

  1. const recorderManager = wx.getRecorderManager();
  2. recorderManager.onStart(() => {
  3. console.log('录音开始');
  4. });
  5. recorderManager.onStop((res) => {
  6. const tempFilePath = res.tempFilePath;
  7. // 上传tempFilePath到后端ASR服务
  8. uploadToASR(tempFilePath);
  9. });
  10. // 启动录音(采样率16000Hz,格式mp3)
  11. recorderManager.start({
  12. format: 'mp3',
  13. sampleRate: 16000,
  14. encodeBitRate: 128000
  15. });

1.3 后端ASR服务集成

推荐方案:

  1. 自建服务:使用Kaldi、Mozilla DeepSpeech等开源框架部署
  2. 云服务:腾讯云ASR(需独立申请接口权限)

示例上传逻辑:

  1. function uploadToASR(filePath) {
  2. wx.uploadFile({
  3. url: 'https://your-asr-api.com/recognize',
  4. filePath: filePath,
  5. name: 'audio',
  6. formData: {
  7. 'language': 'zh-CN',
  8. 'format': 'mp3'
  9. },
  10. success(res) {
  11. const data = JSON.parse(res.data);
  12. updateUIText(data.result); // 更新界面文本
  13. }
  14. });
  15. }

1.4 实时转写优化

采用WebSocket实现低延迟:

  1. // 客户端分片上传+服务端流式返回
  2. const socketTask = wx.connectSocket({
  3. url: 'wss://your-asr-api.com/stream',
  4. });
  5. // 发送音频分片
  6. function sendAudioChunk(chunk) {
  7. socketTask.send({
  8. data: chunk,
  9. success: () => console.log('分片发送成功')
  10. });
  11. }
  12. // 接收实时结果
  13. socketTask.onMessage((res) => {
  14. const partialResult = JSON.parse(res.data);
  15. updateUIText(partialResult.text);
  16. });

二、文字转语音功能实现

2.1 微信原生TTS方案

使用wx.innerAudioContext播放预置语音:

  1. function playTextAsAudio(text) {
  2. const audioCtx = wx.createInnerAudioContext();
  3. // 实际开发中需预置语音库或使用后端TTS
  4. audioCtx.src = getPreGeneratedAudio(text);
  5. audioCtx.play();
  6. }

2.2 云端TTS集成

推荐腾讯云TTS接口调用示例:

  1. function synthesizeSpeech(text) {
  2. wx.request({
  3. url: 'https://tts.api.qcloud.com/v2/synthesize',
  4. method: 'POST',
  5. data: {
  6. 'Text': text,
  7. 'SessionId': 'unique_session_id',
  8. 'ModelType': 1, // 中文普通话
  9. 'VoiceType': 1010 // 女声
  10. },
  11. success(res) {
  12. const audioUrl = res.data.Audio;
  13. const audioCtx = wx.createInnerAudioContext();
  14. audioCtx.src = audioUrl;
  15. audioCtx.play();
  16. }
  17. });
  18. }

2.3 本地合成优化方案

对于简单需求,可使用离线语音包:

  1. 预生成常用短句音频
  2. 建立文本-音频映射表
  3. 实现动态拼接播放
  1. const audioBank = {
  2. '你好': '/assets/audio/hello.mp3',
  3. '再见': '/assets/audio/bye.mp3'
  4. };
  5. function playFromBank(text) {
  6. const path = audioBank[text] || '/assets/audio/default.mp3';
  7. const audio = wx.createInnerAudioContext();
  8. audio.src = path;
  9. audio.play();
  10. }

三、性能优化与异常处理

3.1 录音质量优化

  • 采样率选择:16kHz(语音识别最佳)
  • 格式选择:mp3(兼容性好)或wav(无损但体积大)
  • 降噪处理:前端简单降噪算法

3.2 错误处理机制

  1. recorderManager.onError((err) => {
  2. console.error('录音错误:', err);
  3. if (err.errMsg.includes('permission')) {
  4. showPermissionDialog();
  5. } else {
  6. retryRecording();
  7. }
  8. });

3.3 用户体验优化

  1. 状态反馈:录音时显示声波动画
  2. 超时处理:30秒无声音自动停止
  3. 结果校验:对ASR结果进行置信度过滤

四、完整实现示例

4.1 语音输入组件

  1. Page({
  2. data: {
  3. isRecording: false,
  4. recognitionResult: ''
  5. },
  6. startRecording() {
  7. this.setData({ isRecording: true });
  8. this.recorderManager.start({
  9. format: 'mp3',
  10. sampleRate: 16000
  11. });
  12. },
  13. stopRecording() {
  14. this.recorderManager.stop();
  15. this.setData({ isRecording: false });
  16. },
  17. onLoad() {
  18. this.recorderManager = wx.getRecorderManager();
  19. this.recorderManager.onStop(this.handleRecordStop.bind(this));
  20. },
  21. handleRecordStop(res) {
  22. uploadToASR(res.tempFilePath).then(text => {
  23. this.setData({ recognitionResult: text });
  24. });
  25. }
  26. });

4.2 语音输出组件

  1. Page({
  2. data: {
  3. inputText: '',
  4. isPlaying: false
  5. },
  6. playSpeech() {
  7. if (!this.data.inputText) return;
  8. this.setData({ isPlaying: true });
  9. synthesizeSpeech(this.data.inputText).finally(() => {
  10. this.setData({ isPlaying: false });
  11. });
  12. }
  13. });

五、常见问题解决方案

5.1 录音权限问题

  • 首次使用需动态申请权限:
    1. wx.authorize({
    2. scope: 'scope.record',
    3. success() { console.log('授权成功') },
    4. fail() { wx.openSetting() }
    5. });

5.2 网络延迟处理

  • 实现本地缓存机制
  • 显示加载状态
  • 设置合理的超时时间(建议ASR请求不超过5秒)

5.3 多语言支持

  • 动态切换ASR语言参数
  • 预置多语言语音包
  • 实现语言自动检测

六、进阶功能建议

  1. 语音指令识别:结合NLP实现复杂指令解析
  2. 声纹识别:增加用户身份验证
  3. 实时对话:构建语音交互对话系统
  4. 无障碍适配:为视障用户提供完整语音导航

通过以上方案,开发者可以在微信小程序中实现稳定高效的语音转文字和文字转语音功能。实际开发时需根据具体需求选择合适的技术路线,并充分考虑性能、兼容性和用户体验等因素。