[useAudio] 尝试停止录音但录音器当前没有在录音状态同步问题:
isCurrentlyRecording() 方法需要等待 MediaRecorder.onstart 事件触发后才返回 trueMediaRecorder 启动可能有延迟或失败移动端浏览器特殊要求:
MediaRecorder 的支持程度不同// 问题代码 - 状态检查不准确
isCurrentlyRecording(): boolean {
return this.isRecording && this.mediaRecorder !== null && this.mediaRecorder.state === 'recording';
}
// this.isRecording 只有在 onstart 事件触发后才为 true
this.mediaRecorder.onstart = () => {
this.isRecording = true;
};
文件:frontend/src/utils/audioProcessor.ts
// 关键修复:使用Promise来等待录音真正开始
const recordingStartPromise = new Promise<void>((resolve, reject) => {
const startTimeout = setTimeout(() => {
reject(new Error('录音启动超时,可能是浏览器兼容性问题'));
}, 5000);
this.mediaRecorder!.onstart = () => {
clearTimeout(startTimeout);
this.isRecording = true;
resolve();
};
});
// 等待录音真正开始
await recordingStartPromise;
新增功能:checkMobileCompatibility()
private checkMobileCompatibility(): { supported: boolean; issues: string[] } {
const issues: string[] = [];
const userAgent = navigator.userAgent.toLowerCase();
const isMobile = /android|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
// iOS Safari 版本检查
if (userAgent.includes('safari') && userAgent.includes('mobile')) {
const match = userAgent.match(/version\/(\d+)/i);
if (match && parseInt(match[1]) < 14) {
issues.push('iOS Safari 版本过低,建议升级到14+');
}
}
return { supported: issues.length === 0, issues };
}
文件:frontend/src/components/VoiceRecorder.tsx
// 移动端友好的错误提示
if (isMobileDevice) {
if (errorMsg.includes('权限')) {
addDebugLog('移动端麦克风权限问题,请检查浏览器设置');
} else if (errorMsg.includes('兼容性')) {
addDebugLog('当前移动端浏览器可能不完全支持录音,建议使用Chrome或Safari最新版');
}
}
增强功能:
创建了专门的移动端录音测试页面:测试用例文件夹/mobile_recording_test.html
功能特点:
const supportedFormats = [
'audio/webm;codecs=opus', // 现代浏览器首选
'audio/webm', // WebM备选
'audio/mp4', // 移动端Safari支持
'audio/ogg;codecs=opus' // Firefox支持
];
移动端浏览器要求在HTTPS环境下才能访问麦克风:
if (location.protocol !== 'https:' && location.hostname !== 'localhost') {
throw new Error('录音功能需要HTTPS环境');
}
确保录音操作在用户主动交互后执行:
// ✅ 正确:在用户点击事件中启动录音
button.addEventListener('click', async () => {
await startRecording();
});
// ❌ 错误:页面自动启动录音
window.addEventListener('load', () => {
startRecording(); // 会被浏览器阻止
});
提供清晰的权限请求引导:
try {
await startRecording();
} catch (error) {
if (error.name === 'NotAllowedError') {
showPermissionGuide(); // 显示权限设置指南
}
}
在开发模式下显示详细的调试信息:
if (process.env.NODE_ENV === 'development' && isMobileDevice) {
showDebugPanel(); // 显示移动端调试面板
}
建议添加错误监控:
window.addEventListener('unhandledrejection', (event) => {
if (event.reason?.message?.includes('录音')) {
// 上报录音相关错误
reportError('mobile_recording_error', event.reason);
}
});
本次修复主要解决了以下问题:
经过修复,移动端录音功能现在应该能够正常工作,用户可以在支持的移动端浏览器中顺利进行录音操作。