简介:本文详细讲解在uniapp框架下实现语音输入功能的方法,覆盖微信小程序和H5端的技术实现细节,提供完整的代码示例和跨端兼容方案。
在移动互联网应用中,语音输入已成为提升用户体验的重要功能。根据2023年移动应用交互报告显示,超过65%的用户希望在聊天、搜索等场景中使用语音输入替代键盘输入。uniapp作为跨平台开发框架,需要同时满足微信小程序和H5端的语音输入需求,这带来了以下技术挑战:
微信小程序提供了wx.getRecorderManager API,核心实现步骤如下:
// 初始化录音管理器const recorderManager = wx.getRecorderManager();// 配置录音参数const options = {duration: 60000, // 录音时长限制sampleRate: 44100, // 采样率numberOfChannels: 1, // 单声道encodeBitRate: 192000, // 编码码率format: 'mp3', // 音频格式frameSize: 50 // 指定帧大小};// 开始录音startRecord() {wx.authorize({scope: 'scope.record',success: () => {recorderManager.start(options);recorderManager.onStart(() => {console.log('录音开始');});},fail: (err) => {console.error('授权失败', err);}});}
微信小程序支持wx.getFileSystemManager处理本地文件,结合后端API实现语音转文字:
// 停止录音并上传stopRecord() {recorderManager.stop();recorderManager.onStop((res) => {const tempFilePath = res.tempFilePath;// 使用wx.uploadFile上传到服务器wx.uploadFile({url: 'https://your-api.com/recognize',filePath: tempFilePath,name: 'audio',success: (res) => {const data = JSON.parse(res.data);console.log('识别结果:', data.result);}});});}
微信小程序需要注意:
H5端主要使用Web Audio API和MediaRecorder API:
// 获取音频流async function startRecording() {try {const stream = await navigator.mediaDevices.getUserMedia({ audio: true });const mediaRecorder = new MediaRecorder(stream);const audioChunks = [];mediaRecorder.ondataavailable = event => {audioChunks.push(event.data);};mediaRecorder.onstop = () => {const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });// 处理音频BlobprocessAudio(audioBlob);};mediaRecorder.start();return { stop: () => mediaRecorder.stop() };} catch (err) {console.error('录音错误:', err);}}
不同浏览器对音频格式的支持存在差异:
| 浏览器 | 支持格式 | 推荐格式 |
|---|---|---|
| Chrome | wav, mp3, ogg | wav |
| Firefox | ogg, wav | ogg |
| Safari | mp3, wav (部分版本) | wav |
解决方案:
function getSupportedFormat() {const isChrome = /Chrome/.test(navigator.userAgent);const isFirefox = /Firefox/.test(navigator.userAgent);if (isFirefox) return 'ogg';if (isChrome) return 'wav';return 'wav'; // 默认}
H5端可通过Web Speech API实现基础识别:
// 检查浏览器支持function checkSpeechRecognition() {return 'webkitSpeechRecognition' in window ||'SpeechRecognition' in window;}// 初始化识别function initRecognition() {const SpeechRecognition = window.SpeechRecognition ||window.webkitSpeechRecognition;const recognition = new SpeechRecognition();recognition.continuous = false;recognition.interimResults = false;recognition.onresult = (event) => {const transcript = event.results[0][0].transcript;console.log('识别结果:', transcript);};recognition.start();}
使用uniapp的条件编译特性:
// #ifdef MP-WEIXIN// 微信小程序特有代码const recorderManager = wx.getRecorderManager();// #endif// #ifdef H5// H5特有代码async function startH5Record() {// H5实现}// #endif
封装跨端语音模块:
const VoiceRecorder = {start: function() {// #ifdef MP-WEIXINreturn this.startWeixin();// #endif// #ifdef H5return this.startH5();// #endif},startWeixin() {// 微信实现},startH5() {// H5实现}}
uniapp插件市场提供了现成的语音插件,如:
uni-voice:支持多端语音录制和播放luch-voice:提供语音识别和合成功能tempFilePath的清理
function handleVoiceError(err) {const errorMap = {'NOT_AUTHORIZED': '请授权麦克风权限','SYSTEM_ERROR': '系统录音错误','NETWORK_ERROR': '网络连接失败'};const errorMsg = errorMap[err.code] || '未知错误';uni.showToast({title: errorMsg,icon: 'none'});}
/components/voice-recordervoice-recorder.vue/pages/indexindex.vue/static/audio/utilsvoice-helper.js
// voice-recorder.vue<template><view class="recorder"><button @click="startRecord">开始录音</button><button @click="stopRecord">停止录音</button><view v-if="isRecording" class="recording-indicator"></view><text v-if="transcript">{{transcript}}</text></view></template><script>import { VoiceHelper } from '@/utils/voice-helper';export default {data() {return {isRecording: false,transcript: ''};},methods: {startRecord() {VoiceHelper.start().then(() => {this.isRecording = true;}).catch(handleVoiceError);},stopRecord() {VoiceHelper.stop().then(result => {this.isRecording = false;this.transcript = result;});}}};</script>
微信小程序录音权限问题:
H5端录音失败:
跨端音频格式不一致:
通过本文的方案,开发者可以在uniapp中高效实现跨端的语音输入功能,覆盖微信小程序和H5两大主流平台。实际开发中,建议结合具体业务需求选择合适的实现方式,并注重用户体验和性能优化。