<template>
  <div>
    <h1>音频实时传输</h1>
    <button @click="toggleRecording">
      {{ isRecording ? '停止传输音频' : '开始传输音频' }}
    </button>
    <p>{{ status }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ws: null,  // WebSocket 连接
      mediaRecorder: null,  // MediaRecorder 实例
      audioChunks: [],  // 音频数据
      status: '点击按钮开始传输音频',
      isRecording: false  // 用于判断是否在录音
    };
  },
  mounted() {
    // 初始化 WebSocket 连接
    this.ws = new WebSocket('ws://192.168.1.60:81'); // 替换为 ESP32 IP 地址
    this.ws.onopen = () => {
      console.log('WebSocket连接已打开');
    };
    this.ws.onmessage = (event) => {
      console.log('接收到来自ESP32的消息:', event.data);
    };
    this.ws.onclose = () => {
      console.log('WebSocket连接已关闭');
    };
  },
  methods: {
    toggleRecording() {
      if (this.isRecording) {
        // 停止录音
        this.stopRecording();
      } else {
        // 开始录音
        this.startRecording();
      }
    },
    
    startRecording() {
      this.status = '开始录音并传输音频...';
      this.audioChunks = [];
      this.isRecording = true;

      navigator.mediaDevices.getUserMedia({ audio: true })
        .then((stream) => {
          this.mediaRecorder = new MediaRecorder(stream);
          this.mediaRecorder.ondataavailable = (event) => {
            this.audioChunks.push(event.data);
            // 每次接收到音频数据时实时发送
            const audioBlob = new Blob([event.data], { type: 'audio/wav' });
            audioBlob.arrayBuffer().then((arrayBuffer) => {
              // 打印音频数据
              console.log('实时音频数据:', new Uint8Array(arrayBuffer));
              // 发送音频数据到 WebSocket
              if (this.ws.readyState === WebSocket.OPEN) {
                this.ws.send(arrayBuffer);  
              }
            });
          };
          this.mediaRecorder.start(100);  // 每100ms捕获一次音频数据
        })
        .catch((err) => {
          console.error('无法访问麦克风:', err);
        });
    },

    stopRecording() {
      this.status = '停止录音';
      this.isRecording = false;

      if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
        this.mediaRecorder.stop();  // 停止录音并发送数据
      }
    }
  }
};
</script>

<style scoped>
button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}
</style>
