Board logo

Title: 语音识别程序 Version 1.x系列,无调用第三方库。 [Print this page]

Author: sky999    Time: 2023-6-10 23:36     Title: 语音识别程序 Version 1.x系列,无调用第三方库。

<!DOCTYPE html>
<html>
<head>
  <?php session_start(); ?>
  <title>语音输入</title>
</head>
<body>
  <div id="chat-box"></div>
  <button type="button" id="voice-button">录音</button>

  <script>
    function addMessage(author, message, time) {
      var chatBox = document.getElementById('chat-box');
      
      if (chatBox.childNodes.length === 0) {
        var placeholderDiv = document.createElement('div');
        placeholderDiv.innerText = '正在等待语音输入...';
        chatBox.appendChild(placeholderDiv);
      }
      
      var lastMessageDiv = chatBox.lastChild;
      if (lastMessageDiv && lastMessageDiv.innerText.startsWith('我:录音中')) {
        chatBox.removeChild(lastMessageDiv);
      }
      
      var messageDiv = document.createElement('div');
      messageDiv.innerHTML = '<strong>' + author + '</strong> (' + time + '): ' + message;
      chatBox.appendChild(messageDiv);
      chatBox.scrollTop = chatBox.scrollHeight;
    }
  
    var recognition = null;
    var isRecording = false;
    var audioChunks = [];
    var startTime = null;
  
    if ('webkitSpeechRecognition' in window) {
      recognition = new webkitSpeechRecognition();
      recognition.continuous = true;
      recognition.interimResults = true;
  
      recognition.onstart = function() {
        isRecording = true;
        startTime = Date.now();
  
        addMessage('我', '录音中...', '');
      };
  
      recognition.onend = function() {
        isRecording = false;

        var chatBox = document.getElementById('chat-box');
        var lastMessageDiv = chatBox.lastChild;
        if (lastMessageDiv && lastMessageDiv.innerText.startsWith('我:录音中')) {
          chatBox.removeChild(lastMessageDiv);
        }

        if (audioChunks.length > 0) {
          var blob = new Blob(audioChunks, { type: 'audio/webm' });
          var audioUrl = URL.createObjectURL(blob);
          var audio = new Audio(audioUrl);

          recognition.onresult = null;

          // Play the recorded audio and then start a new recognition session
          audio.addEventListener('canplaythrough', function() {
            var author = '<?php echo $_SESSION['Mud_username'];?>';
            var time = new Date().toLocaleString();
            addMessage(author, '<a href="' + audioUrl + '" target="_blank">点击播放</a>', time);
            recognition.start();
          });
          audio.play();
        } else {
          recognition.onresult = null;
          recognition.start();
        }
        
        audioChunks = [];
      };
  
      recognition.onerror = function(err) {
        console.error(err);
        isRecording = false;
      };
  
      recognition.onresult = function(event) {
        var result = '';
        for (var i = event.resultIndex; i < event.results.length; ++i) {
          if (event.results.isFinal) {
            result += event.results[0].transcript;
          }
        }
  
        result = result.replace(/[\s\r\n]+/g, ' ').trim();
  
        if (result !== '') {
          var author = '<?php echo $_SESSION['Mud_username'];?>';
          addMessage(author, result, '');

          var formData = new FormData();
          formData.append('text', result);
          formData.append('author', author);
          formData.append('time', new Date().toISOString());
         
          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'save.php');
          xhr.onload = function() {
            if (xhr.status === 200) {
              console.log(xhr.responseText);
            } else {
              console.error('请求失败');
            }
          };
          xhr.send(formData);

          audioChunks = [];
        }
      };
  
      document.getElementById('voice-button').addEventListener('click', function() {
        if (isRecording) {
          recognition.stop();
        } else {
          recognition.start();
        }
      });
    } else {
      alert('浏览器不支持语音输入');
    }
  </script>
</body>
</html>
Author: sky999    Time: 2023-6-11 15:47

<!DOCTYPE html>
<html>
<head>
  <?php
    session_start();
  ?>
  <title>语音输入</title>
</head>
<body>
  <div id="chat-box"></div>
  <button type="button" id="voice-button">录音</button>

  <script>
    // 在聊天窗口中添加一条消息
    function addMessage(sender, message) {
      var chatBox = document.getElementById('chat-box');
      var messageDiv = document.createElement('div');
      messageDiv.innerHTML = '<strong>' + sender + ':</strong> ' + message;
      chatBox.appendChild(messageDiv);
      chatBox.scrollTop = chatBox.scrollHeight;
    }

    var recognition = null;
    var isRecording = false;
    var audioChunks = [];
    var startTime = null;

    if ('webkitSpeechRecognition' in window) {
      recognition = new webkitSpeechRecognition();
      recognition.continuous = true;
      recognition.interimResults = true;

      recognition.onstart = function() {
        console.log('开始录音');
        isRecording = true;
        startTime = Date.now();

        // 清空聊天框的内容
        var chatBox = document.getElementById('chat-box');
        chatBox.innerHTML = '';

        // 显示录音中的提示
        addMessage('我', '录音中...');
      };

      recognition.onend = function() {
        console.log('结束录音');
        isRecording = false;

        // 隐藏录音中的提示
        var chatBox = document.getElementById('chat-box');
        var lastMessageDiv = chatBox.lastChild;
        if (lastMessageDiv && lastMessageDiv.innerText === '我:录音中...') {
          chatBox.removeChild(lastMessageDiv);
        }

        // 显示录音完成的提示
        if (audioChunks.length > 0) {
          addMessage('我', '录音完成,用时 ' + Math.round((Date.now() - startTime) / 1000) + ' 秒');
        }
      };

      recognition.onerror = function(err) {
        console.error(err);
        isRecording = false;
      };

      recognition.onresult = function(event) {
        var result = '';
        for (var i = event.resultIndex; i < event.results.length; ++i) {
          if (event.results.isFinal) {
            result += event.results[0].transcript;
          }
        }

        // 去除空格和回车符等特殊字符
        result = result.replace(/[\s\r\n]+/g, ' ').trim();

        if (result !== '') {
          console.log('语音识别结果:' + result);

          // 确定发送者的语言,使用 PHP 中的 $_SESSION 进行获取登录的用户名
          var sender = '<?php echo $_SESSION['Mud_username'];?>';

          // 将语音输入结果添加到聊天框
          addMessage(sender, '');

          // 将语音文件上传到服务器
          var formData = new FormData();
          formData.append('text', result);
          formData.append('author', sender);
          formData.append('time', new Date().toISOString());

          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'save.php');
          xhr.onload = function() {
            if (xhr.status === 200) {
              console.log(xhr.responseText);
            } else {
              console.error('请求失败');
            }
          };
          xhr.send(formData);

          // 重置录音缓冲区
          audioChunks = [];
        } else {
          console.log('语音识别结果为空');
        }
      };
    } else {
      alert('浏览器不支持语音输入');
    }

    var voiceButton = document.getElementById('voice-button');
    voiceButton.innerHTML = '粤语录音';
    voiceButton.addEventListener('mousedown', function(event) {
      event.preventDefault();
      if (!isRecording) {
        recognition.lang = 'zh-HK';
        voiceButton.innerHTML = '粤语录音';
        recognition.start();
      } else {
        recognition.stop();
      }
    });

    recognition.ondataavailable = function(event) {
      audioChunks.push(event.data);
    };
  </script>
</body>
</html>


这是version 1.01
Author: sky999    Time: 2023-6-11 15:56

语音识别程序 version1.02

<!DOCTYPE html>
<html>
<head>
  <?php
    session_start();
  ?>
  <title>语音输入</title>
</head>
<body>
  <div id="chat-box"></div>
  <button type="button" id="voice-button">录音</button>

  <script>
    // 在聊天窗口中添加一条消息
    function addMessage(sender, message) {
      var chatBox = document.getElementById('chat-box');
      var messageDiv = document.createElement('div');
      messageDiv.innerHTML = '<strong>' + sender + ':</strong> ' + message;
      chatBox.appendChild(messageDiv);
      chatBox.scrollTop = chatBox.scrollHeight;
    }

    var recognition = null;
    var isRecording = false;
    var audioChunks = [];
    var startTime = null;

    if ('webkitSpeechRecognition' in window) {
      recognition = new webkitSpeechRecognition();
      recognition.continuous = true;
      recognition.interimResults = true;

      recognition.onstart = function() {
        console.log('开始录音');
        isRecording = true;
        startTime = Date.now();

        // 清空聊天框的内容
        var chatBox = document.getElementById('chat-box');
        chatBox.innerHTML = '';

        // 显示录音中的提示
        addMessage('我', '录音中...');
      };

      recognition.onend = function() {
        console.log('结束录音');
        isRecording = false;

        // 隐藏录音中的提示
        var chatBox = document.getElementById('chat-box');
        var lastMessageDiv = chatBox.lastChild;
        if (lastMessageDiv && lastMessageDiv.innerText === '我:录音中...') {
          chatBox.removeChild(lastMessageDiv);
        }

        // 显示录音完成的提示
        if (audioChunks.length > 0) {
          addMessage('我', '录音完成,用时 ' + Math.round((Date.now() - startTime) / 1000) + ' 秒');
        }
      };

      recognition.onerror = function(err) {
        console.error(err);
        isRecording = false;
      };

      recognition.onresult = function(event) {
        var result = '';
        for (var i = event.resultIndex; i < event.results.length; ++i) {
          if (event.results[i].isFinal) {
            result += event.results[i][0].transcript;
          }
        }

        // 去除空格和回车符等特殊字符
        result = result.replace(/[\s\r\n]+/g, ' ').trim();

        if (result !== '') {
          console.log('语音识别结果:' + result);

          // 确定发送者的语言,使用 PHP 中的 $_SESSION 进行获取登录的用户名
          var sender = '<?php echo $_SESSION['Mud_username'];?>';

          // 将语音输入结果添加到聊天框
          addMessage(sender, result);

          // 将语音文件上传到服务器
          var formData = new FormData();
          formData.append('text', result);
          formData.append('author', sender);
          formData.append('time', new Date().toISOString());

          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'save.php');
          xhr.onload = function() {
            if (xhr.status === 200) {
              console.log(xhr.responseText);
            } else {
              console.error('请求失败');
            }
          };
          xhr.send(formData);

          // 重置录音缓冲区
          audioChunks = [];
        } else {
          console.log('语音识别结果为空');
        }
      };
    } else {
      alert('浏览器不支持语音输入');
    }

    var voiceButton = document.getElementById('voice-button');
    voiceButton.innerHTML = '粤语录音';
    voiceButton.addEventListener('mousedown', function(event) {
      event.preventDefault();
      if (!isRecording) {
        recognition.lang = 'zh-HK';
        voiceButton.innerHTML = '粤语录音';
        recognition.start();
      } else {
        recognition.stop();
      }
    });

    recognition.ondataavailable = function(event) {
      audioChunks.push(event.data);
    };
  </script>
</body>
</html>
[ 本帖最后由 sky999 于 2023-6-11 15:58 编辑 ]
Author: sky999    Time: 2023-6-11 22:39

version 1.03 这是我的使用版本了。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <?php
    session_start();
  
$tid = $_GET['tid'];
$fid= $_GET['fid'];


  ?>

  <title>语音输入</title>
</head>
<body>

<iframe src ="post_disply2.php?tid=<?php echo  $_GET['tid']; ?>&fid=<?php echo  $_GET['fid']; ?>"  style="width: 100%; height: 40vh;"> </iframe>
  


  <div style="display: flex; justify-content: center;">
    <button type="button" id="voice-button" style="font-size: 1.5rem; padding: 1rem 2rem;">开始录音</button>
  </div>

  <div id="chat-box" style="margin-top: 2rem;"></div>


  <script>
    // 在聊天窗口中添加一条消息
    function addMessage(sender, message) {
      var chatBox = document.getElementById('chat-box');
      var messageDiv = document.createElement('div');
      messageDiv.innerHTML = '<strong>' + sender + ':</strong> ' + message;
      chatBox.appendChild(messageDiv);
      chatBox.scrollTop = chatBox.scrollHeight;
    }

    var recognition = null;
    var isRecording = false;
    var audioChunks = [];
    var startTime = null;

    if ('webkitSpeechRecognition' in window) {
      recognition = new webkitSpeechRecognition();
      recognition.continuous = true;
      recognition.interimResults = true;

      recognition.onstart = function() {
        console.log('开始录音');
        isRecording = true;
        startTime = Date.now();

        // 清空聊天框的内容
        var chatBox = document.getElementById('chat-box');
        chatBox.innerHTML = '';

        // 显示录音中的提示
        addMessage('我', '录音中...');
      };

      recognition.onend = function() {
        console.log('结束录音');
        isRecording = false;

        // 隐藏录音中的提示
        var chatBox = document.getElementById('chat-box');
        var lastMessageDiv = chatBox.lastChild;
        if (lastMessageDiv && lastMessageDiv.innerText === '录音中...') {
          chatBox.removeChild(lastMessageDiv);
        }

        // 显示录音完成的提示
        if (audioChunks.length > 0) {
          addMessage('我', '录音完成,用时 ' + Math.round((Date.now() - startTime) / 1000) + ' 秒');
        }
      };

      recognition.onerror = function(err) {
        console.error(err);
        isRecording = false;
      };

      recognition.onresult = function(event) {
        var result = '';
        for (var i = event.resultIndex; i < event.results.length; ++i) {
          if (event.results[i].isFinal) {
            result += event.results[i][0].transcript;
          }
        }

        // 去除空格和回车符等特殊字符
        result = result.replace(/[\s\r\n]+/g, ' ').trim();

        if (result !== '') {
          console.log('语音识别结果:' + result);

          // 确定发送者的语言,使用 PHP 中的 $_SESSION 进行获取登录的用户名
          var sender = '<?php echo $_SESSION['Mud_username'];?>';

          var fid = '<?php echo $fid ;?>';
          var tid = '<?php echo $tid ;?>';

          // 将语音输入结果添加到聊天
          addMessage(sender, result);

          // 将语音文件上传到服务器
          var formData = new FormData();

        //formData.append('text', result);
          formData.append('cont', result);
          formData.append('author', sender);
          formData.append('tid', tid);
          formData.append('fid', fid);
          formData.append('time', new Date().toISOString());

          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'insert-disply_newstyle.php');
          xhr.onload = function() {
            if (xhr.status === 200) {
              console.log(xhr.responseText);
            } else {
              console.error('请求失败');
            }
          };
          xhr.send(formData);

          // 重置录音缓冲区
          audioChunks = [];
        } else {
          console.log('语音识别结果为空');
        }
      };
    } else {
      alert('浏览器不支持语音输入');
    }

    var voiceButton = document.getElementById('voice-button');
    voiceButton.innerHTML = '粤语录音';
    voiceButton.addEventListener('mousedown', function(event) {
      event.preventDefault();
      if (!isRecording) {
        recognition.lang = 'zh-HK';
        voiceButton.innerHTML = '粤语录音';
        recognition.start();
      } else {
        recognition.stop();
      }
    });

    recognition.ondataavailable = function(event) {
      audioChunks.push(event.data);
    };
  </script>



</body>
</html>
正式使用环境中使用了。

[ 本帖最后由 sky999 于 2023-6-11 22:40 编辑 ]
Author: sky999    Time: 2023-6-12 11:11

代码太长了,要换一种方式来保存才行。
Author: sky999    Time: 2023-6-12 11:11

测试一下这种方式

Att: native.php (2023-6-12 11:11, 554 bytes) / Number of times this attachment has been downloaded 19
http://service.caffz.com/mud/AbyssalSwamp/index/attachment.php?aid=1989
Author: sky999    Time: 2023-6-12 11:12

改进txt方式

[ 本帖最后由 sky999 于 2023-6-12 11:16 编辑 ]

Att: audio1.txt (2023-6-12 11:16, 5.13 K) / Number of times this attachment has been downloaded 15
http://service.caffz.com/mud/AbyssalSwamp/index/attachment.php?aid=1990
Author: sky999    Time: 2023-6-12 11:17

还是采用php整个文件上传好了。
Author: sky999    Time: 2023-6-12 13:48

增加了ajax无刷新技术进去

不错,挺好用的。

Att: audio2.php (2023-6-12 13:48, 516 bytes) / Number of times this attachment has been downloaded 12
http://service.caffz.com/mud/AbyssalSwamp/index/attachment.php?aid=1992

Att: post_disply.php (2023-6-12 13:48, 6.71 K) / Number of times this attachment has been downloaded 13
http://service.caffz.com/mud/AbyssalSwamp/index/attachment.php?aid=1993

Att: audio1.php (2023-6-12 13:48, 5.13 K) / Number of times this attachment has been downloaded 22
http://service.caffz.com/mud/AbyssalSwamp/index/attachment.php?aid=1994
Author: sky999    Time: 2023-6-12 13:48

一个小例子,可以继续进行新的创作。




Welcome AbyssalSwamp (http://service.caffz.com/mud/AbyssalSwamp/index/) caffz.com