AudioToWord.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <template>
  2. <div>
  3. <el-page-header @back="goBack" content="语音转文字"/>
  4. <div class="bank"></div>
  5. <el-card header="语音转文字">
  6. <el-card>
  7. <el-input :readonly="true" id="word" v-model="word"></el-input>
  8. </el-card>
  9. <el-card>
  10. <el-button type="primary" @click="audioCHangeWord"><span v-if="isListening">语音识别中...</span><span v-else>语音识别</span></el-button>
  11. </el-card>
  12. </el-card>
  13. </div>
  14. </template>
  15. <script>
  16. export default {
  17. name: "AudioToWord",
  18. data() {
  19. return {
  20. word: "",
  21. isListening: false, // 判断是否在语音监听中
  22. }
  23. },
  24. methods: {
  25. audioCHangeWord() {
  26. var that = this;
  27. that.word = "";
  28. // 创建SpeechRecognition对象
  29. // eslint-disable-next-line no-undef
  30. var recognition = new webkitSpeechRecognition();
  31. console.log("recognition1", recognition);
  32. if (!recognition) {
  33. // eslint-disable-next-line no-undef
  34. recognition = new SpeechRecognition();
  35. }
  36. console.log("recognition2", recognition);
  37. console.log(11);
  38. // 设置语言
  39. recognition.lang = 'zh-CN';
  40. console.log(22);
  41. // 开始语音识别
  42. recognition.start();
  43. that.isListening = true;
  44. console.log(33);
  45. // 监听识别结果
  46. recognition.onresult = function (event) {
  47. var result = event.results[0][0].transcript;
  48. console.log("监听结果:", result);
  49. that.word = result;
  50. };
  51. // 监听错误事件
  52. recognition.onerror = function (event) {
  53. that.isListening = false;
  54. that.$message("监听语音失败:"+event.error);
  55. console.error(event.error);
  56. };
  57. // 监听结束事件(包括识别成功、识别错误和用户停止)
  58. recognition.onend = function () {
  59. that.isListening = false;
  60. console.log("语音识别停止");
  61. };
  62. },
  63. goBack() {
  64. this.$router.push({ path: "/entry" })
  65. }
  66. }
  67. }
  68. </script>
  69. <style>
  70. </style>