websocket+pcm-player实现pcm音频播放

//安装pcm-player
npm install pcm-player

//引入pcm-player
import PCMPlayer from 'pcm-player'

this.player.continue();  //播放音频
this.player.pause();  //暂停音频
this.player.volume();  //设置音量
this.player.destroy();  //销毁实例
// 创建实例
createPCMPlayer() {
  this.player = new PCMPlayer({
    encoding: "16bitInt", // 采样位数
    channels: 1, // 单通道
    sampleRate: 16000, // 采样率
    flushingTime: 1000, // pcm刷新间隔
    onstatechange: (node, event, type) => {}, // 播放状态变化事件
    onended: (node, event) => {}, // 播放结束事件
  });
},



initVoiceWebSocket() {
  if (typeof WebSocket === "undefined") {
    console.log("您的浏览器不支持socket");
  } else {
    const that = this;
    const wsUrl = `ws://192.168.1.1:8080/pcm?audioId=abcd1234`;
    // 实例化socket
    this.socket = new WebSocket(wsUrl);
    this.socket.onopen = function () {
      ws_heartCheck.start(); // 启动心跳
      console.log("指挥室拾音器WebSocket连接已建立");
      // 在连接建立后,可以发送消息到服务器
    };
    this.socket.onmessage = this.websocketonmessage;
    this.socket.onerror = this.websocketonerror;
    this.socket.onclose = this.websocketclose;
    // WebSocket心跳检测
    let ws_heartCheck = {
      timeout: 30000, // 30秒一次心跳
      timeoutObj: null, // 执行心跳的定时器
      serverTimeoutObj: null, // 服务器超时定时器
      // 启动方法
      start: function () {
        this.timeoutObj = setInterval(function () {
          // 这里发送一个心跳信息,后端收到后,返回一个消息,在onmessage拿到返回的心跳(信息)就说明连接正常
          that.socket.send(JSON.stringify({ funId: "voiceHeart", userId: "" }));
          // 如果超过一定时间还没重置,说明后端主动断开了
        }, this.timeout);
      },
      // 重置方法
      reset: function () {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
      },
    };
  }
}



async websocketonmessage(e) {
  const data = await e.data.arrayBuffer();
  const audioData = new Uint16Array(data);
  this.player.feed(audioData.buffer); // 将PCM音频数据写入pcm-player
  this.player.volume(3);  //设置音频音量大小
  this.player.continue();
},
websocketonerror(e) {
  //连接错误
  console.log("WebSocket连接发生错误");
  // 如果需要重连
  // setTimeout(() => {
  //   this.initVoiceWebSocket();
  // }, 2000);
},
websocketclose(e) {
  //连接关闭
  if (this.socket !== null) {
    this.socket.close();
  }
},
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值