Flutter实现音频回声消除(AEC)需求咨询及问题排查
解决Flutter语音识别麦克风拾取扬声器声音的问题
Flutter方案(基于audio_session库)
你之前的配置未生效,大概率是会话模式或选项匹配不当,调整参数试试——重点启用回声消除相关的系统策略,改用更贴合语音识别场景的会话模式:
import 'package:audio_session/audio_session.dart'; import 'package:speech_to_text/speech_to_text.dart'; Future<void> setupAudioSession() async { final session = await AudioSession.instance; await session.configure(const AudioSessionConfiguration( avAudioSessionCategory: AVAudioSessionCategory.playAndRecord, avAudioSessionCategoryOptions: AVAudioSessionCategoryOptions.duckOthers | AVAudioSessionCategoryOptions.allowBluetoothA2dp, avAudioSessionMode: AVAudioSessionMode.voiceChat, avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.notifyOthersOnDeactivation, )); // 必须激活会话才能让配置生效 await session.setActive(true); } // 初始化语音识别前先执行音频会话配置 void initSpeechRecognition() async { final speech = SpeechToText(); await setupAudioSession(); final isAvailable = await speech.initialize(); if (isAvailable) { speech.listen( onResult: (result) { // 处理识别结果逻辑 }, ); } }
注意:要确保在播放音频、启动语音识别前完成会话配置,如果有其他音频插件占用资源,需先停用对应会话再激活当前配置。
Swift原生方案(通过MethodChannel调用)
如果Flutter层配置仍不生效,直接调用iOS原生代码配置AVAudioSession:
- Flutter侧创建MethodChannel:
import 'package:flutter/services.dart'; class NativeAudioSession { static const MethodChannel _channel = MethodChannel('native_audio_session'); static Future<void> setupSession() async { try { await _channel.invokeMethod('configureSession'); } on PlatformException catch (e) { print('配置失败: ${e.message}'); } } }
- iOS端
AppDelegate.swift中实现配置逻辑:
import AVFoundation import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let controller = window?.rootViewController as! FlutterViewController let audioChannel = FlutterMethodChannel(name: "native_audio_session", binaryMessenger: controller.binaryMessenger) audioChannel.setMethodCallHandler { call, result in if call.method == "configureSession" { let session = AVAudioSession.sharedInstance() do { try session.setCategory(.playAndRecord, mode: .voiceChat, options: [.duckOthers, .allowBluetoothA2dp]) try session.setActive(true) result(nil) } catch { result(FlutterError(code: "SESSION_ERROR", message: error.localizedDescription, details: nil)) } } else { result(FlutterMethodNotImplemented) } } GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
初始化语音识别前调用NativeAudioSession.setupSession()即可。
核心要点
AVAudioSessionMode.voiceChat会自动触发系统内置的回声消除,这是避免麦克风拾取扬声器声音的关键duckOthers选项会降低其他音频音量,进一步减少扬声器输出被拾取的概率- 务必在iOS项目的
Info.plist中添加麦克风权限声明:NSMicrophoneUsageDescription
内容的提问来源于stack exchange,提问作者Roger_Flutter
相关产品推荐
相关产品推荐

