WXL
2 天以前 665ac635d56031ecdbda1d2eed9f63d4c6ab7015
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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()