如何在 JsSIP 中处理音频流?

How to handle audio stream in JsSIP?

我正在创建 React 应用程序,它使用 JsSIP 库来接听通过 VoIP SIP 提供商发出的呼叫。

我已经创建了一个有两个按钮(接受和拒绝)的页面。它成功地在 SIP 服务器上注册了 SIP 客户端。它也成功接听电话,我可以接听。但是接听电话时听不到任何声音。

正在注册 JsSIP 客户端(在 willReceiveProps 因为我有 props 更改后的连接信息):

const socketHost = 'wss://' + contactCenter.host + ':' + contactCenter.port
const socket = new JsSIP.WebSocketInterface(socketHost)
const configuration = {
    sockets: [socket],
    uri: 'sip:' + contactCenter.login + '@' + contactCenter.host,
    password: contactCenter.password,
    socketHost: socketHost,
}

const coolPhone = new JsSIP.UA(configuration)

coolPhone.on('connected', (e: any) => {
    const messages = ServiceContainer.get<MessageManagerInterface>(ServiceTypes.Messages)
    messages.addSuccess('SIP connected')
})

coolPhone.on('newRTCSession', (e: any) => {
    const messages = ServiceContainer.get<MessageManagerInterface>(ServiceTypes.Messages)
    messages.addAlert('New call')

    const session = e.session

    session.on('failed', this.resetLocalState)
    session.on('ended', this.resetLocalState)

    const numberRegexp = /\"(\d+)\"/
    const fromNumber = (numberRegexp.exec(e.request.headers.From[0].raw))[1]
    const toNumber = (numberRegexp.exec(e.request.headers.Contact[0].raw))[1].slice(1)

    this.setState({
        callReceived: true,
        callSession: session,
        fromNumber: fromNumber,
        toNumber: toNumber,
    })
})

coolPhone.start()

处理回答按钮点击的方法:

private answerCall = () => {
    const messages = ServiceContainer.get<MessageManagerInterface>(ServiceTypes.Messages)
    messages.addSuccess('Call answered')

    const callOptions = {
        mediaConstraints: {
            audio: true, // only audio calls
            video: false
        },
        pcConfig: {
            iceServers: [
                { urls: ["stun:stun.l.google.com:19302"] }
            ],
            iceTransportPolicy: "all",
            rtcpMuxPolicy: "negotiate"
        }
    }

    this.state.callSession.answer(callOptions)

    this.state.callSession.connection.addEventListener('addstream', (event: any) => {
        console.log(event)
        this.audioElement.srcObject = event.stream
    })

    this.audioElement.play()

    this.setState({
        callAnswered: true,
        callReceived: false,
    })
}

我做错了什么?

我解决了问题。

问题出在 this.audioElement.play() 行的位置。

我将其移至 addstream 事件的回调:

this.state.callSession.connection.addEventListener('addstream', (event: any) => {
    console.log(event)
    this.audioElement.srcObject = event.stream
    this.audioElement.play()
})

现在可以正常使用了。希望你也觉得有用。

您可以使用 react-sip npm 库来简化 jssip 在 React 应用程序中的使用: https://www.npmjs.com/package/react-sip

您只需要将您的连接设置作为道具传递给 <SipProvider/>,它将位于您的 React 树顶部附近的某个位置。 这将允许您执行基本的 start/stop/answer 操作并在上下文中查看您的呼叫状态!