You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CocoaPods的WebRTC iOS框架仅作为接收端时如何关闭麦克风占用

问题原因

出现这个问题的原因是WebRTC的iOS框架默认会在检测到音频收发器时,自动初始化音频采集模块并申请麦克风权限,哪怕你将收发器设置为仅接收模式,也不会默认关闭采集逻辑,需要手动配置禁用。

解决方案

场景1:不需要接收播放远端音频

直接删除音频收发器的添加代码即可,WebRTC不会触发音频相关设备调用,自然不会占用麦克风:

RTCRtpTransceiverInit *transceiverInit = [[RTCRtpTransceiverInit alloc] init];
transceiverInit.direction = RTCRtpTransceiverDirectionRecvOnly;
// 移除音频收发器创建逻辑
// [self.peerConnection addTransceiverOfType:RTCRtpMediaTypeAudio init:transceiverInit];
[self.peerConnection addTransceiverOfType:RTCRtpMediaTypeVideo init:transceiverInit];

场景2:需要接收播放远端音频,仅关闭麦克风录制

按以下两步配置即可:

  1. 初始化RTCPeerConnection之前,先配置音频会话,禁用自动采集麦克风:
#import <AVFoundation/AVFoundation.h>
#import <WebRTC/RTCAudioSession.h>

RTCAudioSession *rtcSession = [RTCAudioSession sharedInstance];
[rtcSession lockForConfiguration];
// 开启手动音频控制,禁止WebRTC自动激活麦克风采集
rtcSession.useManualAudio = YES;
// 保留音频播放能力,若不需要播放可设置为NO
rtcSession.isAudioEnabled = YES;
// 将系统音频会话配置为纯播放模式,无需麦克风权限
NSError *err = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&err];
[[AVAudioSession sharedInstance] setActive:YES error:&err];
[rtcSession unlockForConfiguration];
  1. 生成SDP(Offer/Answer)时,添加约束明确指定仅接收、不发送音视频:
RTCMediaConstraints *sdpConstraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:@{
    @"offerToReceiveAudio": @"true",
    @"offerToReceiveVideo": @"true",
    @"offerToSendAudio": @"false",
    @"offerToSendVideo": @"false"
} optionalConstraints:nil];
// 生成SDP时传入上述约束
[self.peerConnection offerForConstraints:sdpConstraints completionHandler:^(RTCSessionDescription * _Nullable sdp, NSError * _Nullable error) {
    // 后续SDP处理逻辑
}];

完成上述配置后,WebRTC就不会再占用麦克风设备,同时可以正常播放远端音视频流。

内容的提问来源于stack exchange,提问作者wochao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:45:03