vue+websocket实现语音对讲功能

playAudio.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
    }
  },
  mounted() {
    // this.startCall()
  },
  methods: {
    initWs1() {
      // 连接 websocket,边端发送音频流
      const httpType = location.protocol === 'https:' ? 'wss://' : 'ws://'
      this.ws = new WebSocket(
        httpType + `${location.host}/websocket/audio/web1`
      )
      // this.ws = new WebSocket('ws://10.10.225.77:1041')
      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('error', 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
        // 由于只创建了一个音轨,这里只取第一个频道的数据
        const inputData = inputBuffer.getChannelData(0)
        // 通过socket传输数据,实际上传输的是Float32Array
        if (this.ws.readyState === 1) {
          this.ws.send(inputData)
        }
      }
    },
    // 关闭麦克风
    stopCall() {
      this.play = false
      this.mediaStack.getTracks()[0].stop()
      this.scriptNode.disconnect()
    }
  }
}
</script>
  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
实现在Spring Boot和Vue中使用WebSocket实现实时聊天的过程如下: 1. 后端使用Spring Boot,首先需要在pom.xml文件中添加依赖项以支持WebSocket和Spring Boot的WebSocket集成。例如: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建一个WebSocket配置类,用于配置WebSocket处理程序和端点。例如: ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new ChatHandler(), "/chat").setAllowedOrigins("*"); } } ``` 3. 创建WebSocket处理程序,用于处理WebSocket连接、消息发送和接收。例如: ```java @Component public class ChatHandler extends TextWebSocketHandler { private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); for (WebSocketSession currentSession : sessions) { currentSession.sendMessage(new TextMessage(payload)); } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } } ``` 4. 在Vue中使用`vue-native-websocket`或`vue-socket.io`等库来创建WebSocket连接并处理消息。例如: ```javascript import VueNativeSock from 'vue-native-websocket' Vue.use(VueNativeSock, 'ws://localhost:8080/chat', { format: 'json', reconnection: true, store: VuexStore // 如果需要将消息存储到Vuex中,可以提供一个Vuex store }) ``` 5. 在Vue组件中使用WebSocket连接,发送和接收消息。例如: ```javascript this.$socket.send('Hello') // 发送消息 this.$socket.onMessage((message) => { console.log(message) // 收到消息 }) ``` 通过上述步骤,就可以在Spring Boot和Vue中使用WebSocket实现实时聊天功能。当用户在Vue组件中发送消息时,消息将通过WebSocket连接发送到后端的Spring Boot应用程序,然后由WebSocket处理程序将消息广播给所有连接的客户端。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gaiery

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值