【发布时间】:2016-09-10 22:09:54
【问题描述】:
我正在尝试找出一种可靠的方法将字符串数组传递给语音合成 API,并在说出每个数组项之间暂停。例如。说第 1 项,暂停 x 秒,说第 2 项,等等。
我尝试使用 API 的 onend 方法/事件,但它只工作了几次,然后就完全停止工作,从那时起背靠背读取其余的数组项。
建议?
var dropdown = $('#item-select'),
interval = $('#item-interval').val() * 1000,
itemBtn = $('#item-btn'),
stopBtn = $('#item-stop'),
items = {
'first': ['hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine', 'hello, sunshine'],
'second': ['hello, world', 'hello, world', 'hello, world', 'hello, world', 'hello, world', 'hello, world', 'hello, world', 'hello, world', 'hello, world', 'hello, world', 'hello, world', 'hello, world', 'hello, world']
};
if ('speechSynthesis' in window) {
function speak(text) {
var msg = new SpeechSynthesisUtterance();
msg.text = text;
speechSynthesis.speak(msg);
msg.addEventListener('end', function(e) {
speechSynthesis.pause();
window.setTimeout(function() {
speechSynthesis.resume();
}, interval);
});
}
itemBtn.on('click', function(evt) {
currItem = items[dropdown.val()];
for (var phrase in currItem) {
speak(currItem[phrase]);
}
});
stopBtn.on('click', function(evt) {
speechSynthesis.cancel();
});
} else {
console.log('Voice synthesis isn\'t supported in your browser.');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='item-select'>
<option selected value='first'>First Item</option>
<option value='second'>Second Item</option>
</select>
<label for='item-interval'>Interval (seconds)</label>
<input id='item-interval' max='10' name='item-interval' type='range' value='2'>
<button id='item-btn'>Speak!</button>
<button id='item-stop'>CEASE FIRE</button>
【问题讨论】:
标签: javascript text-to-speech speech-synthesis