//安装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();
}
},