我正在使用VOIP服务构建一个应用程序。现在,我将我的应用程序与CallKit
集成,以便处理来电请求。
当应用程序停留在前台或后台时,它们在接听电话时工作正常。但问题是,当屏幕被锁定时,我试图接听电话,但不幸的是,即使我解锁了屏幕,我也听不到两侧的音频。
如何解决这个问题?
来电报告方式如下:
func reportIncomingCall(uuid: UUID, handle: String, hasVideo: Bool = false, completion: ((NSError?) -> Void)?) {
// 1.
print("This is UUID === ", uuid)
configureAudioSession()
let update = CXCallUpdate()
update.remoteHandle = CXHandle(type: .phoneNumber, value: handle)
update.hasVideo = hasVideo
provider.reportNewIncomingCall(with: uuid, update: update) { error in
if error == nil {
// 3.
self.configureAudioSession()
let call = CallKitCallInit(uuid: uuid, handle: handle)
self.callKitManager.add(call: call)
lastCallUUID = uuid
print("UUID === ", uuid)
} else {
}
// 4.
completion?(error as NSError?)
}
}
这就是我设置音频的方式
func configureAudioSession() {
let session = AVAudioSession.sharedInstance()
do{
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {
print("========== Error in setting category (error.localizedDescription)")
}
do {
try session.setMode(AVAudioSessionModeVoiceChat)
} catch {
print("========= Error in setting mode (error.localizedDescription)")
}
do {
try session.setPreferredSampleRate(44100.0)
} catch {
print("======== Error setting rate (error.localizedDescription)")
}
do {
try session.setPreferredIOBufferDuration(0.005)
} catch {
print("======== Error IOBufferDuration (error.localizedDescription)")
}
do {
try session.setActive(true)
} catch {
print("========== Error starting session (error.localizedDescription)")
}
}
当我在屏幕锁定时接听电话时,我可以看到它在configureAudioSession()
函数中抛出的错误。
为什么在屏幕锁定时无法设置音频?
我添加了的代码行
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
// 1.
guard let call = callKitManager.callWithUUID(uuid: action.callUUID) else {
action.fail()
return
}
// 2.
configureAudioSession()
// 3.
call.answer()
// 4.
action.fulfill()
}
这是configureAudioSession
func configureAudioSession() {
let session = AVAudioSession.sharedInstance()
do{
try session.setCategory(AVAudioSession.Category.playAndRecord,
mode: AVAudioSession.Mode.voiceChat,
options: [])
} catch {
print("========== Error in setting category (error.localizedDescription)")
}
do {
try session.setPreferredSampleRate(44100.0)
} catch {
print("======== Error setting rate (error.localizedDescription)")
}
do {
try session.setPreferredIOBufferDuration(0.005)
} catch {
print("======== Error IOBufferDuration (error.localizedDescription)")
}
do {
try session.setActive(true)
} catch {
print("========== Error starting session (error.localizedDescription)")
}
}
在配置音频会话时,您可以尝试使用AVAudioSessionModeVoiceChat而不是AVAudioSsessionModeMoviePlayback模式。