SIP.js的0.20.0版本是使用typescript开源的JavaScript库
npm install sip.js
<script lang="ts">
import { UserAgent, UserAgentOptions, Registerer, Inviter, SessionState } from 'sip.js'
const transportOptions = {
server: "wss://xxxxx.xxxx" // SIP Websocket 服务器的 Websocket URL
}
const uri = UserAgent.makeURI("sip:分机号@服务器地址")
const userAgentOptions: UserAgentOptions = {
authorizationPassword: '', // 分机密码
authorizationUsername: '', // 分机号
transportOptions,
uri
}
const userAgent = new UserAgent(userAgentOptions) // 创建 SIP 用户代理
const registerer = new Registerer(userAgent)
userAgent.start() // 连接
.then(() => {
registerer.register() // 注册,向服务器进行身份验证并接收消息
const target: any = UserAgent.makeURI("sip:被叫号码@服务器地址")
const inviter = new Inviter(userAgent, target);
inviter.invite() // 拨号
})
</script>
- 挂断电话,如果是使用的简单用户,那么直接调用simpleUser.hangup()即可,使用完全API的用户,需要判断下通话状态,接通前的建立阶段和接通后的确立阶段挂断电话调用的方法不同
inviter.stateChange.addListener((state: SessionState) => {
switch (state) {
case SessionState.Initial: console.log('SessionState.Initial') // 最初
break;
case SessionState.Establishing: console.log('SessionState.Establishing') // 建立
break;
case SessionState.Established: console.log('SessionState.Established') // 确立
break;
case SessionState.Terminating: console.log('SessionState.Terminating') // 终止
case SessionState.Terminated: console.log('SessionState.Terminated') // 结束
break;
default:
throw console.log(`Unknown session state.`)
}
})
- 建立阶段使用
inviter.cancel()
,确立阶段使用inviter.bye()
- 简单用户的demo,简单用户的方法都很简单直接调用方法即可
<script lang="ts">
import { SimpleUser,SimpleUserOptions,SimpleUserDelegate} from 'sip.js/lib/platform/web'
import { UserAgent} from 'sip.js'
let displayName = "分机号"
let webSocketServer = "wss://Websocket URL"
let target = "sip:被叫号码@服务器地址"
let uri = UserAgent.makeURI("sip:分机号@服务器地址")
let simpleUserOptions: SimpleUserOptions = {
media: {
remote: {
audio: document.getElementById('audio')
}
},
userAgentOptions: {
displayName,
authorizationPassword: '',
authorizationUsername: '',
uri
}
}
let simpleUser = new SimpleUser(webSocketServer,simpleUserOptions)
/* 连接 */
simpleUser.connect()
/* 注册 */
simpleUser.register()
/* 拨号 */
simpleUser.call(target,{inviteWithoutSdp: false})
/* 挂断 */
simpleUser.hangup()
/* 断开连接 */
simpleUser.disconnect()
</script>