# JS練習_終極密碼機 透過連接API,製作聲音接收器,接收器辨識使用者的發聲,判斷是否符合設定的數字。 - 純HTML畫面  - 成品畫面  ## JS ### getRandomNum() 使用`Math.random` 創造 0 ~ 1的數字,在乘上100且使用`Math.floor`讓產生數字0~99,最後再加一。 利用console.log檢查是否產生0~100的數字 ```.js const randomNum = getRandomNum(); console.log("number: ",randomNum); function getRandomNum(){ return Math.floor(Math.random()*100) +1; } ``` #### web Speech API Web Speech API 裡面有兩個功能「語音轉文字(Speech Recognition)」跟「文字轉語音(Speech Synthesis )」兩種,本次例子是使用後面「語音轉文字」這個部分。 - 因為每個瀏覽器支援的部分不同,在導入時要加上`webkit`字樣以方便我們驅動API。 ```.js window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; ``` - 建構一個物件實體。使用SpeechRecognition()建構式建立物件。 ```.js //create object let recognition = new window.SpeechRecognition(); ``` - 常用方法: - speechrecognition.start(): 讓API 開始辨識。 - result event - 代表辨識使用這說的話,每段話都會存在 results 這個陣列裡面,如果要獲取所辨識的值,可以直接用數字從陣列中取出。 - 本例透過result()呼叫`getSpeakWord()`這個方法; ```.js recognition.addEventListener('result', getSpeakWord); ``` ##### getSpeakWord() API辨識使用者的發聲,可先以console.log檢查是否成功接收聲音。因為得到的是一串陣列,利用索引值取出聲音資料。  ```.js function getSpeakWord(e){ // console.log(e) const msg = e.results[0][0].transcript; console.log(msg) } ``` - [SpeechRecognition小科普](https://developer.mozilla.org/zh-CN/docs/Web/API/Location/reload) #### writeMessage() 在getSpeakWord 函式裡,呼叫寫入呼叫字的函式`writeMessage()`。 - 此函式為改變原先在html已設定好id為msg的html內容。 ```.js function writeMessage(msg){ $('#msg').html( ` <div>You said:</div> <span class="box">${msg}</span> <div>Go Higher</div> `); } ``` #### checkNum() 設定判斷條件,首先先設定變數num,將`+msg`賦予給num。這邊 ==+== 是代表將string型別的msg轉型為number型別。 - 確認是否為數字。 - 判斷與randomNum的大小別,給予提示。 - 猜對了顯示文字恭喜,結束遊戲。 - `end event` 使用end event,重新呼叫start() 讓使用者可以根據提示繼續猜下一個數字。 ```.js recognition.addEventListener('end',function(){ recognition.start(); }) ``` #### click event 當猜對數字時,畫面有個button,設定綁定點擊觸發reload()事件,讓使用者能再玩一次。  ```.js //click event document.body.addEventListener('click',function(e){ if(e.target.id == "play-again"){ window.location.reload(); } }) ``` - [刷新頁面小科普](https://developer.mozilla.org/zh-CN/docs/Web/API/Location/reload) ###### tags: `javascript`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up