import JsSIP from 'jssip'
|
|
class SipService {
|
constructor() {
|
this.ua = null
|
this.currentSession = null
|
}
|
|
// 初始化SIP客户端
|
init(config) {
|
this.ua = new JsSIP.UA({
|
sockets: [new JsSIP.WebSocketInterface(config.wsUrl)],
|
uri: config.sipUri,
|
password: config.password,
|
display_name: config.displayName,
|
realm: config.realm,
|
ha1: config.ha1,
|
register: true
|
})
|
|
this.ua.start()
|
|
// 注册事件监听
|
this.ua.on('registered', () => {
|
console.log('SIP注册成功')
|
})
|
|
this.ua.on('registrationFailed', (e) => {
|
console.error('SIP注册失败:', e)
|
})
|
|
// 监听来电
|
this.ua.on('newRTCSession', (data) => {
|
this.handleIncomingCall(data.session)
|
})
|
}
|
|
// 一键拨号
|
makeCall(targetNumber) {
|
if (!this.ua) {
|
console.error('SIP客户端未初始化')
|
return
|
}
|
|
const options = {
|
eventHandlers: {
|
progress: (e) => console.log('呼叫中...'),
|
failed: (e) => console.error('呼叫失败:', e),
|
ended: (e) => console.log('通话结束'),
|
confirmed: (e) => console.log('通话已接通')
|
},
|
mediaConstraints: { audio: true, video: false },
|
rtcOfferConstraints: { offerToReceiveAudio: 1 }
|
}
|
|
this.currentSession = this.ua.call(`sip:${targetNumber}`, options)
|
this.setupAudio(this.currentSession)
|
}
|
|
// 挂断当前通话
|
endCall() {
|
if (this.currentSession) {
|
this.currentSession.terminate()
|
this.currentSession = null
|
}
|
}
|
|
// 处理音频流
|
setupAudio(session) {
|
session.connection.addEventListener('addstream', (e) => {
|
const audioElement = document.getElementById('remoteAudio')
|
if (audioElement) {
|
audioElement.srcObject = e.stream
|
}
|
})
|
}
|
|
// 处理来电
|
handleIncomingCall(session) {
|
if (session.direction === 'incoming') {
|
console.log('来电:', session.remote_identity.uri.toString())
|
// 这里可以触发UI通知
|
}
|
}
|
}
|
|
export default new SipService()
|