发布于 2026-01-06 0 阅读
0

使用 Svelte 的语音控制笔记应用程序

使用 Svelte 的语音控制笔记应用程序

应用介绍

我使用 Web Speech API 和 Svelte 构建了一个名为“语音笔记”的演示应用程序。该应用程序提供以下功能:
1) 通过语音和键盘输入记笔记;
2) 收听已创建的笔记;
3) 删除已创建的笔记。

语音 API

Web Speech API 使您能够将语音数据集成到 Web 应用程序中。Web Speech API 分为两部分:语音合成(文本转语音)和语音识别(语音转文本)。

注意 -语音 API 仅支持 Chrome 和 Firefox 浏览器。

YouTube 上有演示视频

移动设计

替代文字

完整代码

https://github.com/karkranikhil/voice-notes

演示

https://voice-notes-nh00avakc.now.sh/

语音API高级概述。

1. 检查 API 支持

try {
    let SpeechRecognition =
      window.SpeechRecognition || window.webkitSpeechRecognition;
    var recognition = new SpeechRecognition();
  } catch (e) {
    console.error(e);
  }
Enter fullscreen mode Exit fullscreen mode

2. 语音转文本事件处理程序

let recordingText = `Press the Play button to Start recording.`; // use this in HTML
//recognition.continuous - If false, the recording will stop after a few seconds of silence.
// When true, the silence period is longer (about 15 seconds)
recognition.continuous = true;

// onresult called every time the Speech API captures Voice.
recognition.onresult = function(event) {
    let current = event.resultIndex;

// Get a transcript of what was said.
    let transcript = event.results[current][0].transcript;
    console.log(transcript);
  };

// Trigger on start
  recognition.onstart = function() {
 // setting the text to inform user about the action
    recordingText =
      "Voice recognition Started. Try speaking into the microphone.";
  };
// Trigger on end
  recognition.onspeechend = function() {
// setting the text to inform user about the action
    recordingText = "Voice recognition turned off.";
  };
// Trigger on error
  recognition.onerror = function(event) {
    if (event.error == "no-speech") {
// setting the text to inform user about the action
      recordingText = "No Voice was detected. Try again.";
    }
  };
Enter fullscreen mode Exit fullscreen mode

3. 文本转语音事件处理程序

function readOutLoud(message) {
    let speech = new SpeechSynthesisUtterance();
    speech.text = message;
    speech.volume = 1;
    speech.rate = 1;
    speech.pitch = 1;
    window.speechSynthesis.speak(speech);
  }
Enter fullscreen mode Exit fullscreen mode

参考

https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API

文章来源:https://dev.to/karkranikhil/voice-control-notes-take-application-using-svelte-1kek