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

如何通过Linphone全局callStateChanged闭包获取当前通话状态

我来帮你搞定这个Linphone通话状态获取的问题!你想通过那个全局的callStateChanged闭包拿到当前通话状态,核心就是把回调注册好,同时把状态存到全局变量里方便随时取用,具体步骤如下:

1. 先定义全局变量存储当前通话状态

你需要一个全局(或者类级别的)变量来保存实时的通话状态,这样在闭包外的任何地方都能访问到:

var currentCallState: LinphoneCallState = LinphoneCallIdle // 默认初始化为空闲状态
2. 完整实现callStateChanged闭包并注册到Linphone核心

你给出的代码有部分截断,我帮你补全完整的逻辑,并且一定要记得把这个回调注册到LinphoneCore实例上,否则不会触发:

// 完整的callStateChanged闭包实现
let callStateChanged: LinphoneCoreCallStateChangedCb = { (lc: OpaquePointer?, call: OpaquePointer?, callState: LinphoneCallState, message: UnsafePointer<Int8>?) in
    // 第一步:更新全局的当前通话状态
    currentCallState = callState
    
    // 第二步:根据不同状态做自定义处理(比如打印日志、更新UI)
    switch callState {
    case LinphoneCallIdle:
        print("通话状态:空闲")
    case LinphoneCallIncomingReceived:
        print("通话状态:收到来电")
    case LinphoneCallOutgoingInit:
        print("通话状态:正在呼出")
    case LinphoneCallOutgoingProgress:
        print("通话状态:呼出中,对方响铃")
    case LinphoneCallConnected:
        print("通话状态:通话已连接")
    case LinphoneCallStreamsRunning:
        print("通话状态:媒体流已启动")
    case LinphoneCallPaused:
        print("通话状态:通话已暂停")
    case LinphoneCallPausedByRemote:
        print("通话状态:对方暂停了通话")
    case LinphoneCallUpdating:
        print("通话状态:通话正在更新")
    case LinphoneCallUpdatedByRemote:
        print("通话状态:对方发起通话更新")
    case LinphoneCallReleased:
        print("通话状态:通话已结束")
    case LinphoneCallError:
        let errorMsg = message != nil ? String(cString: message!) : "未知错误"
        print("通话状态:发生错误 - \(errorMsg)")
    default:
        print("通话状态:未知状态 \(callState.rawValue)")
    }
}

// 注册回调到LinphoneCore实例(假设你已经初始化好lc这个核心实例)
if let core = lc {
    linphone_core_set_call_state_changed_callback(core, callStateChanged, nil)
}
3. 在应用其他地方获取当前状态

现在你可以在任何需要的地方直接访问currentCallState变量,就能拿到实时的通话状态了,比如做业务判断或者更新UI:

// 示例:判断当前是否处于活跃通话中
if currentCallState == LinphoneCallConnected || currentCallState == LinphoneCallStreamsRunning {
    print("当前正在通话")
} else {
    print("当前未在通话")
}
几个重要注意事项
  • 确保LinphoneCore实例已经正确初始化,不然回调注册会失效
  • 如果是在UIKit/SwiftUI里更新UI,一定要切换到主线程!因为Linphone的回调是在后台线程触发的,直接更新UI会崩溃:
    case LinphoneCallConnected:
        DispatchQueue.main.async {
            // 在这里更新UI,比如切换到通话界面、显示通话时长等
        }
    
  • 应用退出或者LinphoneCore销毁时,最好显式移除回调,避免内存泄漏(Linphone虽然会自动处理,但显式操作更稳妥):
    if let core = lc {
        linphone_core_set_call_state_changed_callback(core, nil, nil)
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:25:34