DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>语音转文字title>
<style>
textarea {
width: 100%;
height: 50px;
}
style>
head>
<body>
<div>
<textarea shape="" coords="" href="" alt="" id="area" placeholder="请说点什么...">textarea>
<button id="speek">麦克风button>
<button id="addBtn">发布button>
<ul id="text">ul>
div>
<script>
window.onload = () => {
console.log('页面加载完毕');
const area = document.querySelector('#area');
const speek = document.querySelector('#speek');
const addBtn = document.querySelector('#addBtn');
const text = document.querySelector('#text');
const recognition = new webkitSpeechRecognition();
let isSpeek = false;
recognition.continuous = true;
recognition.interimResults = true;
recognition.lang = 'zh-CN';
recognition.onresult=function(event) {
console.log(event, 'event')
let result = ''
for(let i = event.resultIndex;i <= event.resultIndex; i++) {
if (event.results[i].isFinal) {
result += event.results[i][0].transcript;
}
}
area.value = result
}
speek.addEventListener('click', () => {
if(isSpeek) {
recognition.stop();
isSpeek = false;
return;
}
recognition.start();
isSpeek = true;
})
addBtn.addEventListener('click', () => {
const li = document.createElement('li');
li.textContent = area.value;
text.appendChild(li);
area.value = '';
})
}
script>
body>
html>
<template>
<div>
<button @click="playVoice">播放语音button>
div>
template>
<script>
const synth = window.speechSynthesis
const msg = new SpeechSynthesisUtterance()
export default {
data() {
return {};
},
mounted(){
},
methods: {
playVoice() {
this.handleSpeak('小朋友,你是否有很多问号') // 传入需要播放的文字
},
// 语音播报的函数
handleSpeak(text) {
msg.text = text; // 文字内容: 小朋友,你是否有很多问号
msg.lang = "zh-CN"; // 使用的语言:中文
msg.volume = 1; // 声音音量:1
msg.rate = 1; // 语速:1
msg.pitch = 1; // 音高:1
synth.speak(msg) // 播放
},
// 语音停止
handleStop(e) {
msg.text = e
msg.lang = "zh-CN"
synth.cancel(msg)
}
}
};
script>
提示:本文图片等素材来源于网络,若有侵权,请发邮件至邮箱:810665436@qq.com联系笔者 删除。
笔者:苦海123
其它问题可通过以下方式联系本人咨询:
QQ:810665436
微信:ConstancyMan