簡體   English   中英

如何在語音合成中改變聲音?

[英]How to change voice in Speech Synthesis?

我正在嘗試使用Speechsynthesis的一個簡單示例。

<script>

voices = window.speechSynthesis.getVoices()
var utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[4];
utterance.lang = voices[4].lang;
window.speechSynthesis.speak(utterance);

</script>

但這會產生一個錯誤,即 voices is undefined。 我發現 getVoices() 是異步加載的。 我看到了這個答案並更新了我的代碼,如下所示以使用回調。

<script>
window.speechSynthesis.onvoiceschanged = function() {
voices = window.speechSynthesis.getVoices()
var utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[4];
utterance.lang = voices[4].lang;
window.speechSynthesis.speak(utterance);
};
</script>

但是由於一些奇怪的原因,這段文字被說了三次而不是一次。 我該如何修復此代碼?

我無法復制您的問題,但嘗試添加一個事件監聽器,以便在加載語音后運行您的函數。

let voices, utterance;

function speakVoice() {
voices = this.getVoices();
utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[1];
speechSynthesis.speak(utterance);
};

speechSynthesis.addEventListener('voiceschanged', speakVoice);

這可以在許多JS Bin類型的演示中看到。 舉些例子:

http://jsbin.com/sazuca/1/edit?html,css,js,output

https://codepen.io/matt-west/pen/wGzuJ

當使用非本地語音時,Chrome會使用voiceschanged事件來查看此行為。 另一個影響是聲音列表通常是三重的。

W3C規范說:

聲音變化的事件

當getVoices方法將返回的SpeechSynthesisVoiceList的內容發生更改時觸發。 示例包括:服務器端綜合,其中列表是異步確定的, 或者是在安裝/卸載客戶端語音時

...所以我認為當Chrome獲得聲音時會觸發一次事件,而當使用第一個非本地聲音時則會觸發兩次。

鑒於似乎沒有辦法區分哪個更改正在觸發事件我一直在使用這個丑陋的代碼:

    // Add voices to dropdown list
    loadVoices();
    // For browsers that use voiceschanged event
    speechSynthesis.onvoiceschanged = function(e) {
        // Load the voices into the dropdown
        loadVoices();
        // Don't add more options when voiceschanged again
        speechSynthesis.onvoiceschanged = null;
    }

其中loadVoices()是將語音添加到選擇選項的函數。 它並不理想,但它適用於所有瀏覽器(使用語音合成),無論它們是否使用onvoices。

剛才遇到了同樣的問題&解決方案很簡單。 只需在全球范圍內聲明聲音,而不僅僅是在 onclick function 中聲明聲音,然后重復兩次

utterance.voice = window.speechSynthesis.getVoices()[Math.floor(Math.random()*6)]
setTimeout(() => {
    utterance.voice = window.speechSynthesis.getVoices()[Math.floor(Math.random()*6)]
}, 1000)

話語是包含 speechSynthesisUtterance() 的變量

與 chrome 的 24 種相比,Brave 瀏覽器僅支持 6 種類型的聲音,這就是為什么我選擇任何隨機聲音 b/w 1-6。

您可以簡單地添加此代碼並在項目中使用SpeechSynthesis,它適用於我。

var su;

su = new SpeechSynthesisUtterance();

su.text = "Hello World";

speechSynthesis.speak(su);

speechSynthesis.cancel();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM