<html>
<head>
<title>demo</title>
</head>
<body>
<input type="text" id="content" value="测试文字转换声音!">
<button onclick="display()">测试</button>
<script>
function display(){
var content = document.getElementById("content").value;
if(!content){
content = "测试文字转换声音";
}
speak({
text: content
}, function() {
console.log('语音播放结束');
}, function() {
console.log('语音开始播放');
});
}
/**
* @description 文字转语音方法
* @public
* @param { text, rate, lang, volume, pitch } object
* @param text 要合成的文字内容,字符串
* @param rate 读取文字的语速 0.1~10 正常1
* @param lang 读取文字时的语言
* @param volume 读取时声音的音量 0~1 正常1
* @param pitch 读取时声音的音高 0~2 正常1
* @returns SpeechSynthesisUtterance
*/
function speak({ text, speechRate, lang, volume, pitch }, endEvent, startEvent) {
if (!window.SpeechSynthesisUtterance) {
console.warn('当前浏览器不支持文字转语音服务')
return;
}
if (!text) {
return;
}
const speechUtterance = new SpeechSynthesisUtterance();
speechUtterance.text = text;
speechUtterance.rate = speechRate || 1;
speechUtterance.lang = lang || 'zh-CN';
speechUtterance.volume = volume || 1;
speechUtterance.pitch = pitch || 1;
speechUtterance.onend = function() {
endEvent && endEvent();
};
speechUtterance.onstart = function() {
startEvent && startEvent();
};
speechSynthesis.speak(speechUtterance);
return speechUtterance;
}
</script>
</body>
</html>
直接复制拷贝html文件里,然后用浏览器打开进行测试即可,文本框直接输入想播放的内容,点击测试