
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/adminlte.min.css">

<style>
  .content {
    overflow: hidden; /* 防止内容区域出现滚动条 */
  }
  .card-body {
    overflow-y: auto; /* 仅在卡片内容超出时显示垂直滚动条 */
  }
</style>

<!-- 添加麦克风样式 -->
<style>
  .microphone-container {
    position: relative;
    display: inline-block;
  }
  
  .microphone-btn {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background-color: #dc3545;
    border: none;
    color: white;
    font-size: 36px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    position: relative;
  }
  
  .microphone-btn:hover {
    background-color: #c82333;
    transform: scale(1.05);
  }
  
  .microphone-btn.recording {
    background-color: #ffc107;
    animation: pulse 1.5s infinite;
  }
  
  .recording-text {
    position: absolute;
    font-size: 12px;
    color: white;
    font-weight: bold;
    text-shadow: 0 0 2px rgba(0,0,0,0.5);
  }
  
  @keyframes pulse {
    0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255,193,7,0.7); }
    70% { transform: scale(1.1); box-shadow: 0 0 0 10px rgba(255,193,7,0); }
    100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255,193,7,0); }
  }
</style>

<body>

<!-- Content Header (Page header) -->
<section class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1>一句话识别 Sentence ASR</h1>
      </div>
      <div class="col-sm-6">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item active">一句话识别</li>
          <li class="breadcrumb-item"><a href="asr_live.html">实时识别</a></li>
          <li class="breadcrumb-item"><a href="asr_file.html">文件识别</a></li>
        </ol>
      </div>
    </div>
  </div><!-- /.container-fluid -->
</section>
<!-- /.content-header -->


<section class="content"> 

  <div class="row justify-content-center"> <!-- 添加row容器并使用justify-content-center类 -->

    <div class="col-md-9">
      <div class="card card-primary card-outline">

        <div class="card-header">
        </div>
        <!-- /.card-header -->

        <div class="card-body text-center">
          <!-- 修改为麦克风图标 -->
          <div class="microphone-container">
            <button 
              class="microphone-btn"
              id="microphoneBtn"
              title="长按启动录音，点击停止"
            >
              <i class="fas fa-microphone"></i>
              <span class="recording-text" id="recordingText" style="display: none;">录音中</span>
            </button>
          </div>
        </div>

        <div class="card-body">
          <div class="form-group" style="display: flex; justify-content: center; align-items: center;">
            <div class="form-check form-check-inline">
              <input class="form-check-input" type="checkbox" id="enableSensword" name="enableSensword" checked>
              <label class="form-check-label" for="enableSensword">启用热词</label>
            </div>
            <div class="form-check form-check-inline ml-4">
              <input class="form-check-input" type="checkbox" id="enableHotword" name="enableHotword" checked>
              <label class="form-check-label" for="enableHotword">启用敏感词</label>
            </div>
          </div>

          <div class="form-group text-center">
            <label for="recognitionResult">识别结果</label>
            <textarea class="form-control" id="recognitionResult" rows="3" cols="16" placeholder="识别结果将显示在这里"></textarea>
          </div>
        </div>

        <div class="card-footer text-right">
          <button type="reset" class="btn btn-default" onclick="reset();"><i class="fas fa-times"></i> 清除</button>
          <!-- 导出按钮 -->
          <button type="button" class="btn btn-success" id="btnExportWav" onclick="exportWav();" disabled>
              <i class="fas fa-download"></i> 导出WAV
          </button>
        </div>

      </div>
    </div>

  </div>
  <!-- /.container-fluid -->
</section>

<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
    <div class="modal-content">
      <img src="images/progress.gif" />
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

</body>


<script src="common/oddrecoder.js"></script>
<script src="common/oddasr.js"></script>

<script src="dist/js/FileSaver.min.js"></script>

<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>

<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>


<script>
  var recorder = null;
  var isRecording = false;
  var longPressTimer = null;
  var microphoneBtn = document.getElementById('microphoneBtn');
  var recordingText = document.getElementById('recordingText');
  
  // 长按启动录音
  microphoneBtn.addEventListener('mousedown', function() {
    if (!isRecording) {
      longPressTimer = setTimeout(function() {
        start_recoder();
      }, 500); // 500毫秒长按触发
    }
  });
  
  // 鼠标抬起或离开取消长按
  microphoneBtn.addEventListener('mouseup', function() {
    if (longPressTimer) {
      clearTimeout(longPressTimer);
      longPressTimer = null;
    }
  });
  
  microphoneBtn.addEventListener('mouseleave', function() {
    if (longPressTimer) {
      clearTimeout(longPressTimer);
      longPressTimer = null;
    }
  });
  
  // 点击停止录音
  microphoneBtn.addEventListener('click', function() {
    if (isRecording) {
      stop_recoder();
    }
  });
  
  // 触摸屏支持
  microphoneBtn.addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (!isRecording) {
      longPressTimer = setTimeout(function() {
        start_recoder();
      }, 500);
    }
  });
  
  microphoneBtn.addEventListener('touchend', function(e) {
    e.preventDefault();
    if (longPressTimer) {
      clearTimeout(longPressTimer);
      longPressTimer = null;
    }
    if (isRecording) {
      stop_recoder();
    }
  });
  
  function start_recoder() {
    if (!recorder) {
      recorder = new OddRecoder();
    }
    if (recorder && !isRecording) {
      recorder.startRecoder();
      isRecording = true;
      microphoneBtn.classList.add('recording');
      recordingText.style.display = 'block';
      microphoneBtn.innerHTML = '<i class="fas fa-microphone"></i><span class="recording-text" id="recordingText">录音中</span>';
      document.getElementById('btnExportWav').disabled = true;
    }
  }
  
  function stop_recoder() {
    if (recorder && isRecording) {
      recorder.stopRecoder();
      isRecording = false;
      microphoneBtn.classList.remove('recording');
      recordingText.style.display = 'none';
      microphoneBtn.innerHTML = '<i class="fas fa-microphone"></i><span class="recording-text" id="recordingText" style="display: none;">录音中</span>';
      document.getElementById('btnExportWav').disabled = false;
      
      // 停止录音后自动上传音频并获取转写结果
      autoTranscribeAudio();
    }
  }

  // 自动转写音频函数
  function autoTranscribeAudio() {
    if (recorder && recorder.audioChunks && recorder.audioChunks.length > 0) {
      try {
        const wavBlob = recorder.exportWav();
        if (wavBlob) {
          console.log('准备上传音频到/v1/asr接口，大小:', wavBlob.size, '字节');
          modalDlg(true);
          update_transmit(1);
          
          // 创建FormData对象并添加音频文件和参数
          const formData = new FormData();
          formData.append("audio", wavBlob, 'recording.wav');
          formData.append("mode", "file"); // 设置模式为file
          formData.append("output_format", "txt"); // 设置输出格式为纯文本
          
          // 检测是否启用热词
          if ($('input[name="enableHotword"]:checked').val() == 'on') {
            const hotwords = "test123";
            console.log("启用热词: ", hotwords);
            formData.append("hotwords", hotwords);
          }
          
          // 发送音频到/v1/asr接口
          $.ajax({
            type: 'POST',
            url: '/v1/asr/sentence',
            data: formData,
            cache: false,
            processData: false,
            contentType: false,
            async: true,
            success: function (data) {
              modalDlg(false);
              update_transmit(0);
              console.log('ASR转写结果:', data);
              
              // 显示转写结果
              if (data.text) {
                console.log('转写成功:\n' + data.text);
                // 这里可以添加代码将转写结果显示在页面上
                $("#recognitionResult").text(data.text+'\n');
              } else if (data.error) {
                console.error('转写失败: ' + data.error);
              }
            }, 
            error: function (xhr, status, error) {
              modalDlg(false);
              update_transmit(0);
              console.error('上传音频出错:', error);
              console.error('XHR状态:', xhr.status, '响应文本:', xhr.responseText);
              console.error('上传音频失败: ' + (xhr.responseJSON?.error || error || '未知错误'));
            }
          });
        }
      } catch (error) {
        console.error('准备音频数据出错: ', error);
        alert('准备转写音频失败: ' + error.message);
      }
    } else {
      alert('没有可转写的录音数据');
    }
  }

  function exportWav() {
    if (recorder && recorder.audioChunks && recorder.audioChunks.length > 0) {
      try {
        const wavBlob = recorder.exportWav();
        if (wavBlob) {
          // 使用FileSaver.js保存文件
          const filename = 'recording_' + new Date().toISOString().replace(/[:.]/g, '-') + '.wav';
          console.log('导出WAV文件:', filename, '大小:', wavBlob.size, '字节');
          
          // 检查浏览器是否支持saveAs函数
          if (typeof saveAs === 'function') {
            saveAs(wavBlob, filename);
          } else {
            // 如果FileSaver.js不可用，使用替代方法
            const url = URL.createObjectURL(wavBlob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(() => {
              document.body.removeChild(a);
              URL.revokeObjectURL(url);
            }, 100);
          }
        }
      } catch (error) {
        console.error('导出WAV文件出错: ', error);
        alert('导出WAV文件失败: ' + error.message);
      }
    } else {
      alert('没有可导出的录音数据');
    }
  }

  function reset() {
    if (recorder) {
      recorder.stopRecoder();
    }
    $("#btnExportWav").prop("disabled", true);
  }

  function hideModalDlg() {
    $("#myModal").modal('hide');
  }

  function modalDlg(show) {
    if (show == true) {
      console.log("show modal dialog");
      $("#myModal").modal({ backdrop: 'false', keyboard: false });
    } else {
      hideModalDlg();
      //setTimeout(hideModalDlg , 3000);
      console.log("hide modal dialog");
    }
  }

  function update_transmit(flag) {
      $.ajaxSetup({ "xhrFields": true });
      $.ajax({
        url: "/update_transmit",
        data: JSON.stringify({ "flag": flag }),
        contentType: "application/json",
        type: "Post",
        traditional: true
      })
  }
</script>
