// 启动或关闭对讲机模式
public func enablePushToTalk(enable: Bool) {
var sendDict: [String: Any] = [
"type": 1105,
]
sendDict.updateValue(myUid, forKey: "senderId")
sendDict.updateValue(robotUid, forKey: "receiverId")
sendDict.updateValue(["enable": enable], forKey: "data")
if let sendData = sendDict.aicall_jsonString.data(using: .utf8) {
let rtcMsg = AliRtcDataChannelMsg()
rtcMsg.type = .custom
rtcMsg.data = sendData
self.rtcEngine.sendDataChannelMessage(rtcMsg)
self.rtcEngine.muteLocalMic(enable, mode: .allAudioMode)
}
}
// 按住讲话,请确保已经启动对讲机模式
public func startPushToTalk() {
var sendDict: [String: Any] = [
"type": 1106,
]
sendDict.updateValue(myUid, forKey: "senderId")
sendDict.updateValue(robotUid, forKey: "receiverId")
if let sendData = sendDict.aicall_jsonString.data(using: .utf8) {
let rtcMsg = AliRtcDataChannelMsg()
rtcMsg.type = .custom
rtcMsg.data = sendData
self.rtcEngine.sendDataChannelMessage(rtcMsg)
// 取消静音麦克风
self.rtcEngine.muteLocalMic(false, mode: .allAudioMode)
}
}
// 完成讲话,请确保已经启动对讲机模式
public func finishPushToTalk() {
var sendDict: [String: Any] = [
"type": 1107,
]
sendDict.updateValue(myUid, forKey: "senderId")
sendDict.updateValue(robotUid, forKey: "receiverId")
if let sendData = sendDict.aicall_jsonString.data(using: .utf8) {
let rtcMsg = AliRtcDataChannelMsg()
rtcMsg.type = .custom
rtcMsg.data = sendData
self.rtcEngine.sendDataChannelMessage(rtcMsg)
// 取消静音麦克风
self.rtcEngine.muteLocalMic(true, mode: .allAudioMode)
}
}
// 取消这次发送,请确保已经启动对讲机模式
public func cancelPushToTalk() {
var sendDict: [String: Any] = [
"type": 1108,
]
sendDict.updateValue(myUid, forKey: "senderId")
sendDict.updateValue(robotUid, forKey: "receiverId")
if let sendData = sendDict.aicall_jsonString.data(using: .utf8) {
let rtcMsg = AliRtcDataChannelMsg()
rtcMsg.type = .custom
rtcMsg.data = sendData
self.rtcEngine.sendDataChannelMessage(rtcMsg)
// 取消静音麦克风
self.rtcEngine.muteLocalMic(true, mode: .allAudioMode)
}
}
// 处理接收到的DataChannel消息
public func onDataChannelMessage(_ uid: String, controlMsg: AliRtcDataChannelMsg) {
if controlMsg.type != .custom {
return
}
let dataDict = (try? JSONSerialization.jsonObject(with: controlMsg.data, options: .allowFragments)) as? [String : Any]
guard let dataDict = dataDict else {
return
}
debugPrint("onDataChannelMessage:\(dataDict)")
if dataDict["type"] as? Int32 == 1007 {
let data = dataDict["data"] as? [String: Any]
if let data = data {
if let enable = data["enable"] as? Bool {
// 服务端已经开启/关闭对讲机模式,参考流程
DispatchQueue.main.async {
self.enablePushToTalk = enable
self.rtcEngine.muteLocalMic(enable, mode: .allAudioMode)
}
}
}
}
// 处理其他消息
...
}