日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

html文字转语音代码,【JavaScript】实现文本转语音功能

發布時間:2024/7/23 javascript 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 html文字转语音代码,【JavaScript】实现文本转语音功能 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

JavaScript 代碼:

// 初始化 speechSynthesis API

const synth = window.speechSynthesis

// 獲取 DOM 節點

const body = document.querySelector('body')

const textForm = document.querySelector('form')

const textInput = document.querySelector('#text-input')

const voiceSelect = document.querySelector('#voice-select')

const rate = document.querySelector('#rate')

const rateValue = document.querySelector('#rate-value')

const pitch = document.querySelector('#pitch')

const pitchValue = document.querySelector('#pitch-value')

let voices = []

function getVoiceList() {

voices = synth.getVoices()

// 循環 voices 數組,并逐一創建一個 option

voices.forEach((voice) => {

const option = document.createElement('option')

option.textContent = voice.name

// 設置 option 屬性

option.setAttribute('data-lang', voice.lang)

option.setAttribute('data-name', voice.name)

voiceSelect.appendChild(option)

})

}

// synth.getVoices() 為異步執行

// synth.getVoices() 方法將在 synth.onvoiceschanged 觸發時運行

// 因此須有如下語句,否則 synth.getVoices() 返回空數組

getVoiceList()

if (synth.onvoiceschanged !== undefined) {

synth.onvoiceschanged = getVoiceList

}

// 發音方法

function speakIt() {

// 若正在發音則直接返回

if (synth.speaking) {

return

}

if (textInput.value != '') {

// 添加 gif 動畫

body.style.background = '#141414 url(./img/wave.gif) repeat'

body.style.backgroundPositionY = '-50px'

// 獲取發音文本

const speakText = new SpeechSynthesisUtterance(textInput.value)

// 發音結束后觸發的方法

speakText.onend = (e) => {

body.style.background = '#141414'

}

// 發音出錯是觸發的方法

speakText.onerror = (e) => {

alert('出現錯誤,請重試。')

}

// 獲取 select 框當前選中的語言項并獲取其 data-name 屬性值

const selectVoice = voiceSelect.selectedOptions[0].getAttribute('data-name')

// 遍歷 voices 數組,在 voice.name 中找到與上方 select 中選擇的語言一致的選項

// 并把它賦值給 speakText.voice

voices.forEach((voice) => {

if (voice.name === selectVoice) {

speakText.voice = voice

}

})

// 設置發音速率

speakText.rate = rate.value

// 設置發音音調

speakText.pitch = pitch.value

// 開始發音

synth.speak(speakText)

}

}

// 提交表單

textForm.addEventListener('submit', (e) => {

e.preventDefault()

speakIt()

})

// 改變速率右側的數值

rate.addEventListener('change', (e) => {

rateValue.textContent = rate.value

})

// 改變音調右側的數值

pitch.addEventListener('change', (e) => {

pitchValue.textContent = pitch.value

})

總結

以上是生活随笔為你收集整理的html文字转语音代码,【JavaScript】实现文本转语音功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。