WebSocket+Vue+SpringBoot实现语音通话

这篇具有很好参考价值的文章主要介绍了WebSocket+Vue+SpringBoot实现语音通话。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

参考文章

  • 整体思路

前端点击开始对话按钮后,将监听麦克风,获取到当前的音频,将其装化为二进制数据,通过websocket发送到webscoket服务端,服务端在接收后,将消息写入给指定客户端,客户端拿到发送过来的二进制音频后再转化播放

  • 注意事项
    由于音频转化后的二进制数据较大,websocket默认的消息传输大小不能被接收,所以需要通过 @OnMessage(maxMessageSize=5242880)注解进行调整

  • Vue代码

<template>
  <div class="play-audio">
    <el-button @click="startCall" ref="start">开始对讲</el-button>
    <el-button @click="stopCall" ref="stop">结束对讲</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ws: null,
      mediaStack: null,
      audioCtx: null,
      scriptNode: null,
      source: null,
      play: true
    }
  },

  methods: {
    initWs1() {
		//设置好友ID
	  let recipientId=localStorage.getItem('userId')=="2"?"1":"2";
      this.ws = new WebSocket('ws://192.168.206.204:8081/video/'+localStorage.getItem('userId')+"/"+recipientId)
      this.ws.onopen = () => {
        console.log('socket 已连接')
      }
      this.ws.binaryType = 'arraybuffer'
      this.ws.onmessage = ({ data }) => {
	 console.log("接收到的数据--》"+ data)
	
		
        // 将接收的数据转换成与传输过来的数据相同的Float32Array
        const buffer = new Float32Array(data)
        // 创建一个空白的AudioBuffer对象,这里的4096跟发送方保持一致,48000是采样率
        const myArrayBuffer = this.audioCtx.createBuffer(1, 4096, 48000)
        // 也是由于只创建了一个音轨,可以直接取到0
        const nowBuffering = myArrayBuffer.getChannelData(0)
        // 通过循环,将接收过来的数据赋值给简单音频对象
        for (let i = 0; i < 4096; i++) {
          nowBuffering[i] = buffer[i]
        }
        // 使用AudioBufferSourceNode播放音频
        const source = this.audioCtx.createBufferSource()
        source.buffer = myArrayBuffer
        const gainNode = this.audioCtx.createGain()
        source.connect(gainNode)
        gainNode.connect(this.audioCtx.destination)
        var muteValue = 1
        if (!this.play) { // 是否静音
          muteValue = 0
        }
        gainNode.gain.setValueAtTime(muteValue, this.audioCtx.currentTime)
        source.start()
      }
      this.ws.onerror = (e) => {
        console.log('发生错误', e)
      }
      this.ws.onclose = () => {
        console.log('socket closed')
      }
	
    },
    // 开始对讲
    startCall() {

      this.play = true
      this.audioCtx = new AudioContext()
      this.initWs1()
	
      // 该变量存储当前MediaStreamAudioSourceNode的引用
      // 可以通过它关闭麦克风停止音频传输

      // 创建一个ScriptProcessorNode 用于接收当前麦克风的音频
      this.scriptNode = this.audioCtx.createScriptProcessor(4096, 1, 1)
      navigator.mediaDevices
        .getUserMedia({ audio: true, video: false })
        .then((stream) => {
          this.mediaStack = stream
          this.source = this.audioCtx.createMediaStreamSource(stream)

          this.source.connect(this.scriptNode)
          this.scriptNode.connect(this.audioCtx.destination)
        })
        .catch(function (err) {
          /* 处理error */
          console.log('err', err)
        })
      // 当麦克风有声音输入时,会调用此事件
      // 实际上麦克风始终处于打开状态时,即使不说话,此事件也在一直调用
      this.scriptNode.onaudioprocess = (audioProcessingEvent) => {
        const inputBuffer = audioProcessingEvent.inputBuffer
		// console.log("inputBuffer",inputBuffer);
        // 由于只创建了一个音轨,这里只取第一个频道的数据
        const inputData = inputBuffer.getChannelData(0)
		console.log("调用")
        // 通过socket传输数据,实际上传输的是Float32Array
        if (this.ws.readyState === 1) {
			
			
			// console.log("发送的数据",inputData);
          this.ws.send(inputData)
        }
      }
    },
    // 关闭麦克风
    stopCall() {
      this.play = false
      this.mediaStack.getTracks()[0].stop()
      this.scriptNode.disconnect()
    }
  }
}
</script>


-java代码
webscoket配置类

package com.example.software.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;




/**
 * @Description: websocket配置
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

webscoket服务类

package com.example.software.service.webscoket;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author:wf
 * @Date 2023/5/14 13:55
 * 消息收发
 **/
@Controller
@ServerEndpoint(value = "/video/{senderID}/{recipientId}")
@Slf4j
public class WebSocketServer {


    /** 当前在线连接数。应该把它设计成线程安全的 */
    private static  int onlineCount = 0;
    /** 存放每个客户端对应的MyWebSocket对象。实现服务端与单一客户端通信的话,其中Key可以为用户标识 */
    private static ConcurrentHashMap<String, Session> webSocketSet = new ConcurrentHashMap<String, Session>();

    /** 与某个客户端的连接会话,需要通过它来给客户端发送数据 */
    private Session WebSocketsession;
    /** 当前发消息的人员编号 */
    private String senderID = "";


    /**
     * 连接建立成功调用的方法
     * @param param 发送者ID,是由谁发送的
     * @param WebSocketsession 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(@PathParam(value = "senderID") String param, @PathParam(value = "recipientId") String recipientId,Session WebSocketsession) {
        System.out.println("人员-------**-------编号:"+param+":加入聊天");
        System.out.println("盆友是:"+recipientId+"");

        //接收到发送消息的人员编号
        senderID = param;
        System.out.println("senderID:"+senderID);
        //设置消息大小最大为10M,这种方式也可以达到效果,或者使用下面的    @OnMessage(maxMessageSize=5242880)
        //The default buffer size for text messages is 8192 bytes.消息超过8192b,自动断开连接

//        WebSocketsession.setMaxTextMessageBufferSize(10*1024*1024);
//        WebSocketsession.setMaxBinaryMessageBufferSize(10*1024*1024);


        //加入map中,绑定当前用户和socket
        webSocketSet.put(param, WebSocketsession);
        //在线数加1
        addOnlineCount();
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (StrUtil.isNotBlank(senderID)) {
            //从set中删除
            webSocketSet.remove(senderID);
            //在线数减1
            subOnlineCount();
        }
    }


    /**
     * 收到客户端消息后调用的方法
     *
     *设置最大接收消息大小
     */
    @OnMessage(maxMessageSize=5242880)
    public void onMessage(@PathParam(value = "senderID") String senderID ,@PathParam(value = "recipientId") String recipientId,InputStream inputStream) {
        System.out.println(senderID+":发送给"+recipientId+"的消息-->"+inputStream);

        try {
            byte[] buff = new byte[inputStream.available()];
            inputStream.read(buff, 0, inputStream.available());
            Session session = webSocketSet.get("2");
            synchronized (session) {
                //给2号发送
                session.getBasicRemote().sendBinary(ByteBuffer.wrap(buff));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }


    /**
     * 为指定用户发送消息
     *
     * @param message 消息内容
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        //加同步锁,解决多线程下发送消息异常关闭
        synchronized (this.WebSocketsession){
            this.WebSocketsession.getBasicRemote().sendText(message);
        }
    }

    /**
     * 获取当前在线人数
     * @return 返回当前在线人数
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 增加当前在线人数
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    /**
     * 减少当前在线人数
     */
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}




  • 测试方法
    1.使用两个浏览器模拟两个用户,首先在浏览器本地存储一个用户ID
    用户A–谷歌浏览器:
    WebSocket+Vue+SpringBoot实现语音通话
    用户B–火狐浏览器
    WebSocket+Vue+SpringBoot实现语音通话
    2.点击按钮,进行测试
    3.关于谷歌浏览器提示TypeError: Cannot read property ‘getUserMedia’ of undefined
    原因:chrome下获取浏览器录音功能,因为安全性问题,需要在localhost或127.0.0.1或https下才能获取权限
    解决方案:
    1.网页使用https访问,服务端升级为https访问,配置ssl证书
    2.使用localhost或127.0.0.1 进行访问
    3.修改浏览器安全配置(最直接、简单)
    a.首先在chrome浏览器中输入如下指令
chrome://flags/#unsafely-treat-insecure-origin-as-secure 

WebSocket+Vue+SpringBoot实现语音通话

b.然后开启 Insecure origins treated as secure
在下方输入栏内输入你访问的地址url,然后将右侧Disabled 改成 Enabled即可
WebSocket+Vue+SpringBoot实现语音通话

c.然后浏览器会提示重启, 点击Relaunch即可
WebSocket+Vue+SpringBoot实现语音通话文章来源地址https://www.toymoban.com/news/detail-457653.html

到了这里,关于WebSocket+Vue+SpringBoot实现语音通话的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • uniapp Vue 使用 sip.js进行语音通话视频通话

    下载或者安装 sip.js 到 uniapp 项目,APP 端在 menifest.json 中配置麦克风权限 menifest.json 中 app 权限配置选中: android.permission.RECORD_AUDIO android.permission.MODIFY_AUDIO_SETTINGS sip.js 低版本 如 V0.13.0 版本的写法 sip.js 高版本如 V0.21.2 用法 (参数同上,只列出 methods 里的部分) APP模式下检测麦

    2024年02月13日
    浏览(120)
  • webRCT实时语音视频通话 结合 vue使用

    前言:最近项目遇到了一个推送视频对话的需求,本身项目就用到了websocket推送,所以直接使用webRCT就行 封装了一个socket.js mounted的中调用connection 就可以了

    2024年02月13日
    浏览(27)
  • unity 使用声网(Agora)实现语音通话

    第一步、先申请一个声网账号 [Agora官网链接](https://console.shengwang.cn/) 第二步在官网创建项目 ,选择无证书模式,证书模式需要tokenh和Appld才能通话 第三步 官网下载SDK 然后导入到unity,也可以直接在unity商店里下载,Agora官网下载链接 第四步 运行官方Demo 1、导入后会有这些

    2024年04月25日
    浏览(31)
  • springboot+websocket+webrtc 仿微信、仿QQ 音视频通话聊天 飞鱼chat IM即时通讯

    仿微信、QQ音视频聊天,文字表情、收发文件图片等功能。本项目使用springboot+websocket+webrtc-bootstrap5+H5+JQuery3.3+mysql实现,可自适应PC端和移动端 git地址在最后 pc端效果图 WebSocket是一种在单个TCP连接上进行全双工通信的协议,这使得客户端和服务器之间的数据交换变得更加简单

    2024年02月04日
    浏览(41)
  • python使用VOSK实现离线语音识别(中文普通话)

    目标:一个代码简单,离线,可直接使用,常用语句准确率还不错,免费的,普通话语音转文本的工具 几番对比下来,VSOK基本满足我的需求,记录一下。 环境 windows 10 / python3.8.10 s1 安装 vosk s2 下载模型 两个模型,一个很小,文件名中带有small字样,另一个就很大了,就我自

    2024年02月11日
    浏览(30)
  • SpringBoot+Vue整合WebSocket实现实时通讯

            在开发过程中,我们经常遇到需要对前台的列表数据,实现实时展示最新的几条数据,或者是调度的任务进度条实现实时的刷新......,而对于这种需求,无状态的http协议显然无法满足我们的需求,于是websocket协议应运而生。websocket协议本质上是一个基于tcp的协议

    2024年02月13日
    浏览(29)
  • 微服务系列文章之 Springboot+Vue实现登录注册

    一、springBoot 创建springBoot项目   分为三个包,分别为controller,service, dao以及resource目录下的xml文件。 添加pom.xml 依赖 UserController.java   UserService.java   User.java (我安装了lombok插件)   UserMapper.java   UserMapper.xml   主干配置 application.yaml   数据库需要建相应得到表 1 2 3 4 CREA

    2024年02月13日
    浏览(23)
  • SpringBoot+Vue 整合websocket实现简单聊天窗口

    1 输入临时名字充当账号使用 2 进入聊天窗口 3 发送消息 (复制一个页面,输入其他名字,方便展示效果) 4 其他窗口效果 pom依赖 WebSocketConfig.java WebSocketServer.java MessageVo.java App.vue

    2024年02月09日
    浏览(35)
  • vue+springboot+websocket实现消息通知,含应用场景

    vue、springboot 实现场景 点击同步之后更新数据,更新时间比较长,因此使用异步,之后该按钮置灰,在数据更新完成之后,服务端通知客户端已经同步成功,通知提示框,用户即可查看数据 前端 1、在对应的页面编写初始化、连接成功,错误,接受信息方法 2、mounted或者cre

    2024年02月11日
    浏览(61)
  • Vue3+springboot通过websocket实现实时通信

    本文章使用vue3+springboot通过websocket实现两个用户之间的实时通信,聊天信息使用mongodb非关系型数据库进行存储。 效果图如下: 用户发送信息  农户收到信息并发送回去 后台消息打印 引入依赖   配置 在config目录下, 创建WebSocketConfig类 创建一个WebSocketServer来 处理连接 用户

    2024年02月05日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包