You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中为SIP.js Session变量绑定trackAdded事件的方法

给SIP.js Session添加trackAdded事件监听器的正确位置

嘿,这事儿其实挺清晰的——你的session是每次点击按钮调用callme方法时才生成的新实例,所以事件监听器必须紧跟在这个session实例创建之后绑定,才能确保监听器能捕获到当前会话的trackAdded事件。

具体来说,你只需要在callme方法里,完成this.session的赋值操作后,立刻调用on方法绑定事件就行。我还结合官方的媒体挂载逻辑,给你补全了音频渲染的代码,直接就能用:

<template>
  <div>
    <button @click="callme">Call Me</button>
    <!-- 新增一个容器专门用来挂载音频元素,避免DOM混乱 -->
    <div id="audio-container"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      session: null,
      ua: null,
    };
  },
  methods: {
    callme() {
      this.session = this.ua.invite('sip:bob@example.com');
      
      // 就在这里添加trackAdded事件监听器!
      this.session.on('trackAdded', (track) => {
        // 只处理音频轨道,过滤掉可能的视频轨道
        if (track.kind === 'audio') {
          // 创建音频元素并绑定媒体流
          const audioElement = document.createElement('audio');
          audioElement.srcObject = new MediaStream([track]);
          // 自动播放(注意:浏览器要求音频播放必须由用户交互触发,这里点击按钮已经满足条件)
          audioElement.play().catch(err => {
            console.error('音频播放失败:', err);
          });
          // 将音频元素挂载到预先准备的DOM容器中
          document.getElementById('audio-container').appendChild(audioElement);
        }
      });

      // 额外建议:监听会话终止事件,清理音频元素避免内存泄漏
      this.session.on('terminated', () => {
        const audioContainer = document.getElementById('audio-container');
        while (audioContainer.firstChild) {
          audioContainer.removeChild(audioContainer.firstChild);
        }
        this.session = null;
      });
    },
  },
  created() {
    this.ua = new SIP.UA({
      uri: 'bob@example.onsip.com',
      transportOptions: {
        wsServers: ['wss://sip-ws.example.com'],
      },
      authorizationUser: '',
      password: '',
    });
  },
};
</script>

核心逻辑说明:

  • 为什么放在callme里? 因为每次点击按钮都会生成全新的session实例,监听器必须绑定到当前这个实例上;如果放在created或者其他生命周期里,此时session还未创建,绑定操作会直接失效。
  • 音频挂载细节:按照官方的实现思路,通过MediaStream将捕获到的音频轨道绑定到audio元素,再挂载到DOM容器中,这样就能正常播放通话音频了。
  • 内存优化:加入terminated事件监听,会话结束时清理DOM中的音频元素并重置session,避免多次调用后残留无用元素占用资源。

内容的提问来源于stack exchange,提问作者Stacy Thompson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:50:34